Thursday, June 30, 2016

ActionController::ActionControllerError in CommentsController#create | Fixed issues

ActionController::ActionControllerError in CommentsController#create | Fixed issues


ActionController::ActionControllerError in CommentsController#create

Posted: 30 Jun 2016 07:36 AM PDT

model:

class Comment < ActiveRecord::Base    belongs_to :post    validates_presence_of :name    validates_length_of :name, :within=> 2..20    validates_presence_of :body  end  

Following is the controller

    class CommentsController < InheritedResources::Base      def comment_params          params.require(:comment).permit(:name, :email, :body, :post_id)      end        def create          @comment = Comment.new(params[:comment_params])          if @comment.save              flash[:notice] = 'Comment was succesfully posted.'              redirect_to(@comment.post)          else              flash[:notice] = "Error creating comments: #{@comment.errors}"              redirect_to(@comment.post)          end      end  end  

All I see is,

ActionController::ActionControllerError in CommentsController#create  Cannot redirect to nil!    Rails.root: c:/sites/myrubyblog    Application Trace | Framework Trace | Full Trace  app/controllers/comments_controller.rb:13:in `create'  

did try the few solutions from previously asked questions, but nothing is helping!

How can I return the highest "valued" element -- per "name" -- in an Array?

Posted: 30 Jun 2016 07:27 AM PDT

I've read a lot of posts about finding the highest-valued objects in arrays using max and max_by, but my situation is another level deeper, and I can't find any references on how to do it.

I have an experimental Rails app in which I am attempting to convert a legacy .NET/SQL application. The (simplified) model looks like Overlay -> Calibration <- Parameter. In a single data set, I will have, say, 20K Calibrations, but about 3,000-4,000 of these are versioned duplicates by Parameter name, and I need only the highest-versioned Parameter by each name. Further complicating matters is that the version lives on the Overlay. (I know this seems crazy, but this models our reality.)

In pure SQL, we add the following to a query to create a virtual table:

n = ROW_NUMBER() OVER (PARTITION BY Parameters.Designation ORDER BY Overlays.Version DESC)  

And then select the entries where n = 1.

I can order the array like this:

ordered_calibrations = mainline_calibrations.sort do |e, f|    [f.parameter.Designation, f.overlay.Version] <=> [e.parameter.Designation, e.overlay.Version] || 1  end  

I get this kind of result:

C_SCR_trc_NH3SensCln_SCRT1_Thd  160  C_SCR_trc_NH3SensCln_SCRT1_Thd  87  C_SCR_trc_NH3Sen_DewPtHiThd_Tbl 310  C_SCR_trc_NH3Sen_DewPtHiThd_Tbl 160  C_SCR_trc_NH3Sen_DewPtHiThd_Tbl 87  

So I'm wondering if there is a way, using Ruby's Enumerable built-in methods, to loop over the sorted array, and only return the highest-versioned elements per name. HUGE bonus points if I could feed an integer to this method's block, and only return the highest-versioned elements UP TO that version number ("160" would return just the second and fourth entries, above).

The alternative to this is that I could somehow implement the ROW_NUMBER() OVER in ActiveRecord, but that seems much more difficult to try. And, of course, I could write code to deal with this, but I'm quite certain it would be orders of magnitude slower than figuring out the right Enumerable function, if it exists.

(Also, to be clear, it's trivial to do .find_by_sql() and create the same result set as in the legacy application -- it's even fast -- but I'm trying to drag all the related objects along for the ride, which you really can't do with that method.)

How create and include Profile in User model (User its model devise)?

Posted: 30 Jun 2016 07:26 AM PDT

1)install user model (its gem devise)

all settings - all is ok

2) rails g scaffold Profile name:string role:string user:preferences

all settings, migration, and add in model User - has_one :profiles

3) In rails console, i dont find binding id

Were i do error? Help pls. Me need one User, one profile before registration..

Why Capybara feature tests don't wait?

Posted: 30 Jun 2016 07:35 AM PDT

I have a small trouble with my tests suite: when I run spec which the checking ajax action on the page, sometimes I get random error

Failure/Error: expect(page).to have_content 'DHH'  

This error shows very rarely (about 1/100), but this very confused me. I decided this a 'race condition' cause, and I add this config in my spec/rails_helper.rb

Capybara.default_max_wait_time = 10  

but this is don't help for me, and I decided add timestamps

  it 'adds new DHH', js: true do      find('#modal_new_dhh').click      fill_in('name', with: 'DHH')        p 'click button'      p Time.now.strftime('%H:%M:%S.%L')      click_button('Submit')        p 'checking content'      p Time.now.strftime('%H:%M:%S.%L')      expect(page).to have_content 'DHH'        p 'after checking content'      p Time.now.strftime('%H:%M:%S.%L')    end  

and see that

"click button"  "17:34:43.083"  "before checking content"  "17:34:43.127"  "after checking content"  "17:34:43.213"  

why Capybara don't wait after click button?

sorry for my bad English

How do I generate a temporary page like confirmation page in rails?

Posted: 30 Jun 2016 06:41 AM PDT

I am using devise and want to redirect users to a confirmation page upon signup, this is what I am doing right now:

users/registrations_controller.html.erb

class Users::RegistrationsController < Devise::RegistrationsController     def confirm_email   end     private     def after_inactive_sign_up_path_for(resource)    users_confirmyouremail_path   end  end  

config/routes.rb

devise_scope :user do         get 'users/confirmyouremail' => 'users/registrations#confirm_email'   end  

I have no problem with redirecting the page after signup. However, I think it is quite weird that anyone can visit the page with url like `host.com/confirmyouremail' and see the confirmation page. Are there any ways I can write a route that will use random code that is allow only for one time visit? Thanks in advance.

HABTM multi "and" query

Posted: 30 Jun 2016 06:35 AM PDT

I have Article and Tag records with HABTM relation.

I need to filter Article by array of tags with "and" query.

With tags below, I need every "Salami" and "Pizza" that are expired.

tags = ["Salami", "Pizza", "Expired"] // items could be any number from 1..n

I came up with following but this returns every "Salami" and "Pizza" which aren't expired. This also return every items expired which aren't Salami nor Pizza

def tags_query      render status: 200, json: Article.includes(:tags).where('tags.name' => params[:tags] )  end  

Can someone help me with this method?

Posted: 30 Jun 2016 07:37 AM PDT

def positioning    tasks = Painting.all.order(:position)    increment = false    tasks.each do |t|      if !increment && t.position == self.position        increment = true        t.position += 1        t.save      elsif increment        t.position += 1        t.save      end    end  end  

this method is for a before_save callback, and works when i add a new painting, but its doing something wrong incrementing the other objects position and later when i want to update any object this is a problem.

Rails eroor while installing

Posted: 30 Jun 2016 06:14 AM PDT

hi can u help me with this problem :

spree install  [WARNING] Spree CMD Installer is deprecated. Please follow installation instructions at https://github.com/spree/spree#getting-started  Would you like to install the default gateways? (Recommended) (yes/no) [yes]   Would you like to install the default authentication system? (yes/no) [yes]   Would you like to run the migrations? (yes/no) [yes]   Would you like to load the seed data? (yes/no) [yes]   Would you like to load the sample data? (yes/no) [yes]        gemfile  spree       gemfile  spree_gateway       gemfile  spree_auth_devise           run  bundle install from "."  Could not find gem 'spree_auth_devise (~> 3.0.0) ruby' in the gems available on this machine.  Run `bundle install` to install missing gems.  

when i am typing bundle install it says :

bundle install  Fetching gem metadata from https://rubygems.org/.............  Fetching additional metadata from https://rubygems.org/..  Resolving dependencies...  Bundler could not find compatible versions for gem "jquery-rails":    In Gemfile:      spree (~> 3.1.0) ruby depends on        spree_frontend (= 3.1.0) ruby depends on          jquery-rails (~> 4.1) ruby        jquery-rails (3.1.4)  

please help me i was creating ecommerce website

Validate model without associated models

Posted: 30 Jun 2016 07:13 AM PDT

I have a model user that has_one business

At certain times I want to validate user on its own without taking into account business.

At the moment if

user.business.valid? is false

this will make user.valid? also false even if the user record on its own is valid.

If in user.rb I do has_one :business, :validate => false it will not take business into account when validating user, but it will then always do it, which is what I dont want.

What is the syntax to call the validation on user without taking the business association into account?

If I do user.business(validate: false).valid? it will ignore the validation on business and user. The above will be true even if user is invalid.

Any ideas?

Update:

Validations:

user.rb

validates :first_name, presence: true

business.rb

validates :name, presence: true

Using rails5.0.0.rc1

Can't access css and js from public folder in development mode in Rails 4.2.6

Posted: 30 Jun 2016 06:02 AM PDT

My issue is almost the same as this one. I couldn't access my css and js which are under public folder in development mode.

This is how I mentioned in layout:

  <link rel="stylesheet" href="/college/css/bootstrap.css">    <link rel="stylesheet" href="/college/css/main.css">    <%= javascript_include_tag "application" %>    <script src="/college/js/admin.js"></script>    <script src="/college/bootstrap.min.js"></script>  

I have tried adding config.serve_static_files = true in development.rb file, but no use. Also there is no error listed in the logs. What might be the mistake?

Rails/SQL: find statistics about a belongs_to relation

Posted: 30 Jun 2016 06:13 AM PDT

I have the following models

class Project    has_many :contributions  end    class Contributor    has_many :contributions  end    class Contribution    belongs_to :contributor    belongs_to :project  end  

I'm trying to find how many contributors contributed in how many projects and sort by number of projects contributed to.

Example:

- Person 1 made contribution to Project 1  - Person 1 made contribution to Project 2  - Person 2 made contribution to Project 1  - Person 2 made contribution to Project 3  - Person 2 made contribution to Project 4  - Person 3 made contribution to Project 4  - Person 3 made contribution to Project 5  

In this case

- Person 1 made 2 contributions in 2 seperate projects.  - Person 2 made 3 contributions in 3 seperate projects.  - Person 3 made 2 contributions in 2 seperate projects.  

which means

- 2 people made 2 contributions  - 1 person made 3 contributions  

Result is: { 2 => 2, 1 => 3 }

Here is what I did:

Contributor.joins(:contributions).order("count(contributions.id) asc").group("contributor.id").count  

This gives me how many contributions by each contributor, but not what I'm looking for.

Ruby on Rails, using activerecord to get all records that have a specified field containing a string in my array

Posted: 30 Jun 2016 06:00 AM PDT

So i know i can do something like this Model.Where('field LIKE ?','%mystring%') to get all records containing my string inside my specified field.

But is there to make it check through an array of strings rather than a single string ?

ruby mongomapper multiple belongs_to on same model

Posted: 30 Jun 2016 05:42 AM PDT

I have a situations where i need to have a model (message) belonging to two entities which are independent document in each other(sender and receiver).

I am currently starting our new app development on ROR and i have already gone through the comparison between mongoid and mongomapper according their use cases, pros and cons. i have settled on mongomapper.

I am deciding data models for mongodb and came down to a situation where i need to have a model associated with two other entity.

class Sender    include MongoMapper::Document    many :messages  end    Class Reciever    include MongoMapper::Document    many: messages  end    Class Messages    include MongoMapper::Document    belongs_to: Sender    belongs_to: Reciever  End   

Will this kind of relationship is supported in mongomapper as i have heard that mongomapper is well maintained by community and lot of quirks while working with associations.

I am new to ROR.

Any help is appreciated

ArgumentError at /login First argument in form cannot contain nil or be empty in Rails 4.2

Posted: 30 Jun 2016 05:42 AM PDT

When I am trying to login this is the error I am getting:

Started GET "/login" for 127.0.0.1 at 2016-06-30 17:56:12 +0530 Processing by SessionsController#new as HTML Rendered sessions/new.html.erb within layouts/home (3.3ms)

Completed 500 Internal Server Error in 90ms (ActiveRecord: 0.3ms) ** [Airbrake] Notice was not sent due to configuration: Environment Monitored? false API key set? true

ArgumentError - First argument in form cannot contain nil or be empty: actionview (4.2.6) lib/action_view/helpers/form_helper.rb:432:in form_for' client_side_validations (4.2.4) lib/client_side_validations/action_view/form_helper.rb:30:in form_for' formtastic (3.1.4) lib/formtastic/helpers/form_helper.rb:174:in block in semantic_form_for' formtastic (3.1.4) lib/formtastic/helpers/form_helper.rb:197:in with_custom_field_error_proc' formtastic (3.1.4) lib/formtastic/helpers/form_helper.rb:173:in semantic_form_for'
app/views/sessions/new.html.erb:9:in
_app_views_sessions_new_html_erb__2338148001530538999_76939480'

This is my sessions/new form:

<%= semantic_form_for(@resource, :as => resource_name, :url => user_session_path, :remote => true, :format => :json, :html => { :id => 'mainLogin' }) do |f| %>          <%= f.inputs do %>          <%= f.input :email, :label => 'Your email address', :input_html => { :placeholder => "Email"} %>                  <%= f.input :password, :label => 'Your password', :input_html => { :placeholder => "Password"} %>              <% end %>            <%= f.buttons do %>            <% if devise_mapping.rememberable? %>              <%= f.input :remember_me, :as => :boolean, :label => "Remember me on this computer", :required => false,  :input_html => {:class => "remember-me"} %>            <% end %>            <%= f.commit_button :label => 'Sign me in', :button_html => {:class => 'login submit button', :disable_with => 'Wait...', :id => 'user_submit' }%>            <% end %>    <% end %>  

This is my sessions_controller:

class SessionsController < Devise::SessionsController    # ssl_required here was causing the re-direct from /login to create to fail with a 302    ssl_allowed :new, :create    ssl_allowed :sign_in_and_redirect, :failure      def create      resource = warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#failure")      puts resource.inspect      return sign_in_and_redirect(resource_name, resource)    end      def sign_in_and_redirect(resource_or_scope, resource=nil)      scope = Devise::Mapping.find_scope!(resource_or_scope)      resource ||= resource_or_scope      sign_in(scope, resource) unless warden.user(scope) == resource      return render :json => {:success => true, :redirect => session[:previous_url] || new_user_report_path(resource)}    end      def failure      # To display the errors below in the view you may have to add      # error_messages_for_devise or something to that effect to the view      # google it :)      return render :json => {:success => false, :errors => ["Login failed."]}    end    end  

It is working in Rails 3.2 version but not working in 4.2.6. Please help me.

braintree hosted fields not rendering fields

Posted: 30 Jun 2016 05:36 AM PDT

I am trying to use the material design braintree hosted fields, I can get the html to render, but is appears as if I have some issue with the javascript conflicting or similar

<!-- Material Design inspired Hosted Fields theme -->    <!-- Icons are taken from the material design library https://github.com/google/material-design-icons/ -->    <!--[if IE 9]>  <style>      .panel {      margin: 2em auto 0;    }    </style>  <![endif]-->    <form id="cardForm">    <div class="panel">      <header class="panel__header">        <h1>Card Payment</h1>      </header>        <div class="panel__content">        <div class="textfield--float-label">              <label class="hosted-field--label" for="card-number"><span class="icon">           <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24"><path d="M0 0h24v24H0z" fill="none"/><path d="M20 4H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V6c0-1.11-.89-2-2-2zm0 14H4v-6h16v6zm0-10H4V6h16v2z"/></svg></span> Card Number          </label>          <div id="card-number" class="hosted-field"></div>        </div>          <div class="textfield--float-label">            <label class="hosted-field--label" for="expiration-date">             <span class="icon">            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24"><path d="M9 11H7v2h2v-2zm4 0h-2v2h2v-2zm4 0h-2v2h2v-2zm2-7h-1V2h-2v2H8V2H6v2H5c-1.11 0-1.99.9-1.99 2L3 20c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 16H5V9h14v11z"/></svg>           </span>            Expiration Date</label>          <div id="expiration-date" class="hosted-field"></div>        </div>            <div class="textfield--float-label">          <label class="hosted-field--label" for="cvv">            <span class="icon">              <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24"><path d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2z"/></svg>              </span>            CVV</label>          <div id="cvv" class="hosted-field"></div>        </div>          <div class="textfield--float-label">            <label class="hosted-field--label" for="postal-code">             <span class="icon">            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24">      <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/></svg>           </span>            Postal Code</label>          <div id="postal-code" class="hosted-field"></div>        </div>      </div>        <footer class="panel__footer">        <button class="pay-button">Pay</button>      </footer>    </div>  </form>    <!-- Load the required client component. -->  <script src="https://js.braintreegateway.com/web/3.0.0-beta.9/js/client.min.js"></script>    <!-- Load Hosted Fields component. -->  <script src="https://js.braintreegateway.com/web/3.0.0-beta.9/js/hosted-fields.min.js"></script>    <script>braintree.client.create({ authorization: 'sandbox_g42y39zw_348pk9cgf3bgyw2b' }, function (err, clientInstance) {    if (err) {      console.error(err);      return;    }    braintree.hostedFields.create({      client: clientInstance,      styles: {        'input': {          'font-size': '16px',          'font-family': 'roboto, verdana, sans-serif',          'font-weight': 'lighter',          'color': 'black'        },        ':focus': { 'color': 'black' },        '.valid': { 'color': 'black' },        '.invalid': { 'color': 'black' }      },      fields: {        number: {          selector: '#card-number',          placeholder: '1111 1111 1111 1111'        },        cvv: {          selector: '#cvv',          placeholder: '111'        },        expirationDate: {          selector: '#expiration-date',          placeholder: 'MM/YY'        },        postalCode: {          selector: '#postal-code',          placeholder: '11111'        }      }    }, function (err, hostedFieldsInstance) {      if (err) {        console.error(err);        return;      }      hostedFieldsInstance.on('focus', function (event) {        var field = event.fields[event.emittedBy];        $(field.container).next('.hosted-field--label').addClass('label-float').removeClass('filled');      });      hostedFieldsInstance.on('blur', function (event) {        var field = event.fields[event.emittedBy];        if (field.isEmpty) {          $(field.container).next('.hosted-field--label').removeClass('label-float');        } else if (event.isValid) {          $(field.container).next('.hosted-field--label').addClass('filled');        } else {          $(field.container).next('.hosted-field--label').addClass('invalid');        }      });      hostedFieldsInstance.on('empty', function (event) {        var field = event.fields[event.emittedBy];        $(field.container).next('.hosted-field--label').removeClass('filled').removeClass('invalid');      });      hostedFieldsInstance.on('validityChange', function (event) {        var field = event.fields[event.emittedBy];        if (field.isPotentiallyValid) {          $(field.container).next('.hosted-field--label').removeClass('invalid');        } else {          $(field.container).next('.hosted-field--label').addClass('invalid');        }      });      $('#cardForm').submit(function (event) {        event.preventDefault();        hostedFieldsInstance.tokenize(function (err, payload) {          if (err) {            console.error(err);            return;          }          alert('Submit your nonce to your server here!');        });      });    });  });  //# sourceURL=pen.js  </script>  

Rails: remote: true from select_tag

Posted: 30 Jun 2016 06:47 AM PDT

I'm calling an AJAX function from a select_tag like so:

<%= select_tag 'quantity', options_from_collection_for_select(order.options), :quantity, :quantity, order.quantity), onchange: "update_price(#{order.id}, this.value);" %>  

And here's the function:

<script type='text/javascript'>    function update_price(order_id, quantity) {      $.ajax({        url: "/cart/" + <%= @cart_transaction.id %> + "/update_quantity",        type: "POST",        data: {          "order_id" : order_id,          "quantity" : quantity },        dataType: "html"      });    }  </script>  

My .js.erb isn't called ever, and I suspect it's because I haven't specified remote: true anywhere, but since I don't have a form per se I don't know how to do that. Any help?

Relevant controller code here:

class CartTransactionsController < ApplicationController    load_and_authorize_resource      respond_to :html, :js      before_filter :set_cart_transaction      def update_quantity      @order = @cart_transaction.orders.find(params[:order_id])      @price = current_user.brand.prices                           .where(template_id: @order.document.template.id)                           .where(quantity: params[:quantity]).first      @order.update_attributes(        price_cents: @price.amount_cents, quantity: params[:quantity]      )      @cart_transaction.save!      respond_to { |format| format.js }    end      private      def set_cart_transaction      @cart_transaction = current_user.cart    end      def cart_transactions_params      params.require(:cart_transaction).permit(        :name, :email, :delivery_address, :comments      )    end  end  

Update

Here's the .js.erb that isn't called for some reason:

console.log("update_quantity.js.erb file");    $('#price_cell').html("<%= j render(partial: 'price', locals: { order: @order }) %>");  $('#subtotals').html("<%= j render(partial: 'subtotals', locals: { cart_transaction: @cart_transaction }) %>");  

Wrong date is saved using simple_form gem

Posted: 30 Jun 2016 05:37 AM PDT

I'm creating a new record with simple_form gem. There are 2 fields (start_date and end_date) which are for the date data.

Can someone help to understand how it is possible that the date saved is a day behind it was entered in the form?

 #<Book:0x0000...   id: 16,   name: "My favorite book",   start_date: Thu, 30 Jun 2016 00:00:00 EEST +03:00,   end_date: Thu, 30 Jun 2016 00:00:00 EEST +03:00,   created_at: Thu, 30 Jun 2016 15:07:57 EEST +03:00,   updated_at: Thu, 30 Jun 2016 15:07:57 EEST +03:00>  

Compare with:

INSERT INTO `books` (`name`, `start_date`, `end_date`, `created_at`, `updated_at`) VALUES ('My favorite book', '2016-06-29 21:00:00', '2016-06-29 21:00:00', '2016-06-30 12:07:57', '2016-06-30 12:07:57')  

I'm trying to save June 30, but it stores June 29. How is it possible?

Detect ngrok from Rails

Posted: 30 Jun 2016 04:42 AM PDT

I am using ngrok in order to test my Rails application integration with PayPal.

Since my application works with subdomains, I would like to detect when call is made from ngrok so I can apply a different behaviour.

Is there any way to configure ngrok to pass some information so I can detect the call comes from there? Or any other way to know that ngrok stands behind the call?

Upgrade Rails 3.2 to 4.2 -> cannot load such file -- resque_scheduler/tasks

Posted: 30 Jun 2016 04:36 AM PDT

I'm trying to upgrade my Rails 3.2 project to Rails 4.2, including all of my dependencies in my Gemfile. I've removed the old version number restrictions from my Gemfile, deleted my Gemfile.lock, and bundle install. It's upgraded everything as I hoped (as far as I can tell), but when I do rake db:setup I get the following error:

p@jarvis ~/g/s/g/n/j/x> rake db:setup --trace  rake aborted!  LoadError: cannot load such file -- resque_scheduler/tasks  /var/lib/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in `require'  /var/lib/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in `block in require'  /var/lib/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:240:in `load_dependency'  /var/lib/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in `require'  /home/p/gop/src/github.com/x/x/x/lib/tasks/resque.rake:2:in `<top (required)>'  /var/lib/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:268:in `load'  /var/lib/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:268:in `block in load'  /var/lib/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:240:in `load_dependency'  /var/lib/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:268:in `load'  /var/lib/gems/2.3.0/gems/railties-4.2.6/lib/rails/engine.rb:658:in `block in run_tasks_blocks'  /var/lib/gems/2.3.0/gems/railties-4.2.6/lib/rails/engine.rb:658:in `each'  /var/lib/gems/2.3.0/gems/railties-4.2.6/lib/rails/engine.rb:658:in `run_tasks_blocks'  /var/lib/gems/2.3.0/gems/railties-4.2.6/lib/rails/application.rb:452:in `run_tasks_blocks'  /var/lib/gems/2.3.0/gems/railties-4.2.6/lib/rails/engine.rb:453:in `load_tasks'  /var/lib/gems/2.3.0/gems/railties-4.2.6/lib/rails/railtie.rb:194:in `public_send'  /var/lib/gems/2.3.0/gems/railties-4.2.6/lib/rails/railtie.rb:194:in `method_missing'  /home/p/gop/src/github.com/x/x/x/Rakefile:7:in `<top (required)>'  /var/lib/gems/2.3.0/gems/rake-11.2.2/lib/rake/rake_module.rb:28:in `load'  /var/lib/gems/2.3.0/gems/rake-11.2.2/lib/rake/rake_module.rb:28:in `load_rakefile'  /var/lib/gems/2.3.0/gems/rake-11.2.2/lib/rake/application.rb:686:in `raw_load_rakefile'  /var/lib/gems/2.3.0/gems/rake-11.2.2/lib/rake/application.rb:96:in `block in load_rakefile'  /var/lib/gems/2.3.0/gems/rake-11.2.2/lib/rake/application.rb:178:in `standard_exception_handling'  /var/lib/gems/2.3.0/gems/rake-11.2.2/lib/rake/application.rb:95:in `load_rakefile'  /var/lib/gems/2.3.0/gems/rake-11.2.2/lib/rake/application.rb:79:in `block in run'  /var/lib/gems/2.3.0/gems/rake-11.2.2/lib/rake/application.rb:178:in `standard_exception_handling'  /var/lib/gems/2.3.0/gems/rake-11.2.2/lib/rake/application.rb:77:in `run'  /var/lib/gems/2.3.0/gems/rake-11.2.2/exe/rake:27:in `<top (required)>'  /usr/local/bin/rake:23:in `load'  /usr/local/bin/rake:23:in `<main>'  

I've tried using gem 'resque-scheduler', '~> 2.5.5' with no luck (saw that recommended somewhere on Google). Also tried supplying the Github path with no luck. Not sure if it's relevant, but my Gemfile has a hyphen and the error has an underscore. Does that have anything to do with it?

This is what my Gemfile looks like:

source 'https://rubygems.org'    gem 'rails'  gem 'postgresql'  gem 'haml'    # Base-62 conversion library  gem 'radix62'    # Generated views will default to haml  gem 'haml-rails'    gem 'resque'  gem 'resque-scheduler'   gem 'activeadmin', github: 'activeadmin'  gem 'activeresource'    group :development do    gem 'pry-rails'  end    # Gems used only for assets and not required  # in production environments by default.  group :assets do    gem 'sass-rails'    gem 'coffee-rails'    gem 'therubyracer', :platforms => :ruby    gem 'uglifier'  end    gem 'jquery-rails'  

Here's my Gemfile.lock:

GIT    remote: git://github.com/activeadmin/activeadmin.git    revision: f0243d495067a8e5b03bd017fe04c5b7de422870    specs:      activeadmin (1.0.0.pre2)        arbre (~> 1.0, >= 1.0.2)        bourbon        coffee-rails        formtastic (~> 3.1)        formtastic_i18n        inherited_resources (~> 1.6)        jquery-rails        jquery-ui-rails        kaminari (~> 0.15)        rails (>= 3.2, < 5.0)        ransack (~> 1.3)        sass-rails        sprockets (< 4)    GEM    remote: https://rubygems.org/    specs:      actionmailer (4.2.6)        actionpack (= 4.2.6)        actionview (= 4.2.6)        activejob (= 4.2.6)        mail (~> 2.5, >= 2.5.4)        rails-dom-testing (~> 1.0, >= 1.0.5)      actionpack (4.2.6)        actionview (= 4.2.6)        activesupport (= 4.2.6)        rack (~> 1.6)        rack-test (~> 0.6.2)        rails-dom-testing (~> 1.0, >= 1.0.5)        rails-html-sanitizer (~> 1.0, >= 1.0.2)      actionview (4.2.6)        activesupport (= 4.2.6)        builder (~> 3.1)        erubis (~> 2.7.0)        rails-dom-testing (~> 1.0, >= 1.0.5)        rails-html-sanitizer (~> 1.0, >= 1.0.2)      activejob (4.2.6)        activesupport (= 4.2.6)        globalid (>= 0.3.0)      activemodel (4.2.6)        activesupport (= 4.2.6)        builder (~> 3.1)      activerecord (4.2.6)        activemodel (= 4.2.6)        activesupport (= 4.2.6)        arel (~> 6.0)      activeresource (4.1.0)        activemodel (~> 4.0)        activesupport (~> 4.0)        rails-observers (~> 0.1.2)      activesupport (4.2.6)        i18n (~> 0.7)        json (~> 1.7, >= 1.7.7)        minitest (~> 5.1)        thread_safe (~> 0.3, >= 0.3.4)        tzinfo (~> 1.1)      arbre (1.0.3)        activesupport (>= 3.0.0)      arel (6.0.3)      bourbon (4.2.7)        sass (~> 3.4)        thor (~> 0.19)      builder (3.2.2)      coderay (1.1.1)      coffee-rails (4.1.1)        coffee-script (>= 2.2.0)        railties (>= 4.0.0, < 5.1.x)      coffee-script (2.4.1)        coffee-script-source        execjs      coffee-script-source (1.10.0)      concurrent-ruby (1.0.2)      erubis (2.7.0)      execjs (2.7.0)      formtastic (3.1.4)        actionpack (>= 3.2.13)      formtastic_i18n (0.6.0)      globalid (0.3.6)        activesupport (>= 4.1.0)      haml (4.0.7)        tilt      haml-rails (0.9.0)        actionpack (>= 4.0.1)        activesupport (>= 4.0.1)        haml (>= 4.0.6, < 5.0)        html2haml (>= 1.0.1)        railties (>= 4.0.1)      has_scope (0.6.0)        actionpack (>= 3.2, < 5)        activesupport (>= 3.2, < 5)      html2haml (2.0.0)        erubis (~> 2.7.0)        haml (~> 4.0.0)        nokogiri (~> 1.6.0)        ruby_parser (~> 3.5)      i18n (0.7.0)      inherited_resources (1.6.0)        actionpack (>= 3.2, < 5)        has_scope (~> 0.6.0.rc)        railties (>= 3.2, < 5)        responders      jquery-rails (4.1.1)        rails-dom-testing (>= 1, < 3)        railties (>= 4.2.0)        thor (>= 0.14, < 2.0)      jquery-ui-rails (5.0.5)        railties (>= 3.2.16)      json (1.8.3)      kaminari (0.17.0)        actionpack (>= 3.0.0)        activesupport (>= 3.0.0)      libv8 (3.16.14.15)      loofah (2.0.3)        nokogiri (>= 1.5.9)      mail (2.6.4)        mime-types (>= 1.16, < 4)      method_source (0.8.2)      mime-types (3.1)        mime-types-data (~> 3.2015)      mime-types-data (3.2016.0521)      mini_portile2 (2.1.0)      minitest (5.9.0)      mono_logger (1.1.0)      multi_json (1.12.1)      nokogiri (1.6.8)        mini_portile2 (~> 2.1.0)        pkg-config (~> 1.1.7)      pg (0.18.4)      pkg-config (1.1.7)      polyamorous (1.3.0)        activerecord (>= 3.0)      postgresql (1.0.0)        pg      pry (0.10.3)        coderay (~> 1.1.0)        method_source (~> 0.8.1)        slop (~> 3.4)      pry-rails (0.3.4)        pry (>= 0.9.10)      rack (1.6.4)      rack-protection (1.5.3)        rack      rack-test (0.6.3)        rack (>= 1.0)      radix62 (1.0.1)      rails (4.2.6)        actionmailer (= 4.2.6)        actionpack (= 4.2.6)        actionview (= 4.2.6)        activejob (= 4.2.6)        activemodel (= 4.2.6)        activerecord (= 4.2.6)        activesupport (= 4.2.6)        bundler (>= 1.3.0, < 2.0)        railties (= 4.2.6)        sprockets-rails      rails-deprecated_sanitizer (1.0.3)        activesupport (>= 4.2.0.alpha)      rails-dom-testing (1.0.7)        activesupport (>= 4.2.0.beta, < 5.0)        nokogiri (~> 1.6.0)        rails-deprecated_sanitizer (>= 1.0.1)      rails-html-sanitizer (1.0.3)        loofah (~> 2.0)      rails-observers (0.1.2)        activemodel (~> 4.0)      railties (4.2.6)        actionpack (= 4.2.6)        activesupport (= 4.2.6)        rake (>= 0.8.7)        thor (>= 0.18.1, < 2.0)      rake (11.2.2)      ransack (1.7.0)        actionpack (>= 3.0)        activerecord (>= 3.0)        activesupport (>= 3.0)        i18n        polyamorous (~> 1.2)      redis (3.3.0)      redis-namespace (1.5.2)        redis (~> 3.0, >= 3.0.4)      ref (2.0.0)      responders (2.2.0)        railties (>= 4.2.0, < 5.1)      resque (1.26.0)        mono_logger (~> 1.0)        multi_json (~> 1.0)        redis-namespace (~> 1.3)        sinatra (>= 0.9.2)        vegas (~> 0.1.2)      resque-scheduler (4.3.0)        mono_logger (~> 1.0)        redis (~> 3.3)        resque (~> 1.26)        rufus-scheduler (~> 3.2)      ruby_parser (3.8.2)        sexp_processor (~> 4.1)      rufus-scheduler (3.2.1)      sass (3.4.22)      sass-rails (5.0.4)        railties (>= 4.0.0, < 5.0)        sass (~> 3.1)        sprockets (>= 2.8, < 4.0)        sprockets-rails (>= 2.0, < 4.0)        tilt (>= 1.1, < 3)      sexp_processor (4.7.0)      sinatra (1.4.7)        rack (~> 1.5)        rack-protection (~> 1.4)        tilt (>= 1.3, < 3)      slop (3.6.0)      sprockets (3.6.2)        concurrent-ruby (~> 1.0)        rack (> 1, < 3)      sprockets-rails (3.1.1)        actionpack (>= 4.0)        activesupport (>= 4.0)        sprockets (>= 3.0.0)      therubyracer (0.12.2)        libv8 (~> 3.16.14.0)        ref      thor (0.19.1)      thread_safe (0.3.5)      tilt (2.0.5)      tzinfo (1.2.2)        thread_safe (~> 0.1)      uglifier (3.0.0)        execjs (>= 0.3.0, < 3)      vegas (0.1.11)        rack (>= 1.0.0)    PLATFORMS    ruby    DEPENDENCIES    activeadmin!    activeresource    coffee-rails    haml    haml-rails    jquery-rails    postgresql    pry-rails    radix62    rails    resque    resque-scheduler    sass-rails    therubyracer    uglifier    BUNDLED WITH     1.12.5  

Testing pessimistic locking with Rails

Posted: 30 Jun 2016 04:29 AM PDT

To get a better understanding of pessimist locking (with InnoDB), I tried to run this code in my Rails application:

Thread.new do    Account.transaction do      account = Account.lock(true).first      account.balance += 250      account.save!    end  end    Thread.new do    Account.transaction do      account = Account.lock(true).first      account.balance += 500      account.save!    end  end  

It actually works, account.balance then contains 750, then 1500 on the next hit. Without locking, it just takes the last thread into consideration and the result is 500.

Is that a dumb test to try out the difference between locking or not? I think I understand the principle of pessimist locking, but not sure though.

How to continue indexing documents in elasticsearch(rails)?

Posted: 30 Jun 2016 05:34 AM PDT

So I ran this command rake environment elasticsearch:import:model CLASS='AutoPartsMapper' FORCE=true to index documents in elasticsearch.In my database I have 10 000 000 records=)...it takes (I think) one day to index this...When indexing was running my computer turned off...(I indexed 2 000 000 documents)Is it possible to continue indexing documents?

syntax error ternary operator in erb

Posted: 30 Jun 2016 03:58 AM PDT

I have one link in view

<%= @entry.user.present? ? link_to @entry.user.nickname , account_path(:user_id=>@entry.user,:key=>"check" ) ,:"data-ajax" => false : "user"  %>  

I write code like below but i am getting syntax error

Please help me to solve it.

Thank you

How to send push notification of multiple devices using apns gem?

Posted: 30 Jun 2016 03:45 AM PDT

I have install apns gem for sending push notification in iPhone device. My push notification code.

# => test push notification    def self.test_push(notification_array)      APNS.host   = 'gateway.sandbox.push.apple.com'      APNS.port   = 2195      APNS.pem    = "#{Rails.root}/public/Xx.pem"      APNS.pass   = 'XXXX'      notifications = []      notification_array.each do |notification|         if notification['devide_token'] != "(null)"          n1 = APNS::Notification.new(notification['device_token'], notification['alert'])      n2 = APNS::Notification.new(notification['device_token'], alert: notification['alert'], badge: 1, sound: 'default', other: { access_token: notification['access_token'], push_type: notification['type'], notification_id: notification['notification_id'], patient_id: notification['p_id'], photovideo_id: notification['pv_id'], team_id: notification['team_id']})      APNS.send_notifications([n1, n2])         end      end      return notifications    end  

Funding source in transfer request using DwollaV2 in rails application

Posted: 30 Jun 2016 03:44 AM PDT

I'm trying to implement money transactions by user's email in my rails application using DwollaV2. The problem is I don't really understand from the documentation what has to be a funding source in the request body and always getting error "Funding source not found".

Steps I'm performing:

  1. Create Dwolla client with key & secret
  2. Get code from Auth
  3. Exchange code for a token, here's how it looks:

# access_token="LQPX..."refresh_token="jjLS..." expires_in=3590 scope="send|fundings" account_id="3481...">

4.Create request body:

id = token.account_id  email = test@gmail.com    request_body = {  _links: {    destination: {      email: "mailto:#{email}"    },    source: {      href: "https://api.dwolla.com/funding-sources/#{id}"    }  },  amount: {    currency: 'USD',    value: amount.to_s  }  }  

5. Perform POST request:

token.post 'transfers', request_body  

Would be grateful for any help or suggestions.

Rails authenticate header access from Angular service

Posted: 30 Jun 2016 03:29 AM PDT

i have an application using rails for handle the backend and angular for the frontend.. i try to add a token in my api, so create new ApiKey model and use

authenticate_or_request_with_http_token  

in my ApiKey model i have name attributes, so the table would be like this:

enter image description here

and this is my controller to check the existing token,

def check_authorization    @access_key = ApiKey.all      authenticate_or_request_with_http_token do |token, options|     @access_key.exists?(access_token: token)    end  end  

this is the angular service.coffee which would passing the token ..

$http.get("/api/#{type}?#{$.param(queryParams)}",  headers: 'Authorization': 'Token token = "30dbe6e6c42d28f4660329171e50fd42c607c40ed6a3396d"')      .then (response) ->        data = response.data  

till here everything work fine,

but i want to make this headers

headers: 'Authorization': 'Token token = "30dbe6e6c42d28f4660329171e50fd42c607c40ed6a3396d"'  

passing the dynamic token, not a static token.. maybe passing the access_token where name is web..

any one can help me ?

Rails: Route Error while trying to update attribute through link_to

Posted: 30 Jun 2016 03:43 AM PDT

ERROR: No route matches [GET] "/bookings/:id/%3E:format"

I want to update an attribute when click on link of 'link_to'..

<%= link_to 'Cancel', '/bookings/:id/(.:format)' %>  

routes.rb

put '/bookings/:id/(.:format)' => "bookings#tocancel"  patch '/bookings/:id/(.:format)' => "bookings#tocancel"  

controller

def tocancel   @booking = Booking.find(params[:id])   @booking.update_attribute(:status, "cancel")   respond_to do |format|    format.html { redirect_to @booking, notice: 'Booking was successfully cancelled.' }    format.json { render :show, status: :ok, location: @booking }  

end

How to solve ActiveAdmin Column 'id' in field list is ambiguous using JOIN issue?

Posted: 30 Jun 2016 03:18 AM PDT

I use JOIN statement in my scope for ActiveAdmin:

scope :not_archived, where("=items.status != 'archived'").joins(:provider)  ...  scope I18n.t('scopes.all'), :not_archived  

And then suddenly MySQL throws an error:

Mysql2::Error: Column 'id' in field list is ambiguous  SELECT id FROM `items` INNER JOIN `providers` ON `providers`.`id` = `items`.`provider_id` WHERE `items`.`status` != 'archived'  

I checked ActiveAdmin sources, but I haven't find code line that forced this selection. Also

except(:select)  

didn't worked.

How to solve this issue?

Couldn't find table with 'id'=all Migration error in Rails 4.2.6

Posted: 30 Jun 2016 03:20 AM PDT

I am getting the following error while running rake db:migrate:

StandardError: An error has occurred, this and all later migrations canceled:

Couldn't find Report with 'id'=all [WHERE "reports"."deleted_at" IS NULL]

Theseare my 2 migration files:

Class AddColorToReports < ActiveRecord::Migration    def self.up      add_column :reports, :button_color, :string        Report.find(:all).each do |r|        r.update_attribute(:color, r.top_stroke_color)      end    end      def self.down      remove_column :reports, :button_color    end  end      class AddDeletedAtToReport < ActiveRecord::Migration    def change      add_column :reports, :deleted_at, :datetime    end  end  

The migrations are fine when running Rail 3.2 and 4.0, but here in 4.2.6, not working.

Please tell me how can I fix this?

Rails web application need to send Desktop Notification targeted to its registered user

Posted: 30 Jun 2016 03:13 AM PDT

Ruby 2.3.0

Rails 4.2.6

In my web application I need to send Desktop Notifications to a target user when a particular task is assigned to him.

Use-case goes like following:

Let's assume following users are available in the system:

  • System Admin (admin@example.com)
  • John (john@example.com)
  • Peter (peter@example.com)

Let's assume system-admin has created following tasks

Task 1) Book an appointment with Bank executive

Task 2) Book a flight to New York

Now system-admin assigns Task 2) to Peter and Task 1) to John

Now there are two scenarios:

  • Users are using the web-application live i.e. they are logged-in.

  • Users are offline.

Scenario 1) - Users are using the web-application live i.e. they are logged-in.

In this case when system-admin assigns the Task 2) to Peter, Peter should receive a Desktop Notification saying You are assigned this task probably with a link to the task. Clicking the link to the task takes Peter to the Task Details page which might contain more details about the task.

Similar should be the behaviour when Task 1) is assigned to John by system-admin.

Scenario 2) - Users are offline

In this case when system-admin assigns the Task 2) to Peter and Task 1) to John both of them should see the Desktop Notification when they log-in to the web-application.

I don't know how much feasible the Scenario 2) is and whether it is possible to implement it or not.

I have no idea about how to implement Desktop Notifications. This is my first attempt and hence clueless. I tried to search the web for possible solutions but I ended up on following libraries:

and some more article links. But all of these focused on how to create and display a Notification. But none of them was convincing enough in guiding me to implement my use-case. Hence decided to seek help from the SO community.

I also found an app Noti and which has published a Ruby gem and a tutorial about implementing Desktop Notifications in a Rails app with Noti. Going through it seems like Noti is what can help me out in my case but Noti can work only when my web application users install Noti's native desktop application on their machine. Thus I am reluctant in pursuing it and am finding for out-of-the-box alternatives.

So can I please get the guidance from the community on my requirement I have mentioned above and what tools or libraries can help me achieve my goal.

Thanks.

Missing method notifications belongs_to has_many

Posted: 30 Jun 2016 03:08 AM PDT

I'm having a lot of trouble getting associations to work in Rails 4.2.2. I have a project and this project can have lots of notifications. What I would like to have is that I can add notifications with:

@project.notifications.build(icon: "icon.jpg", text: "lorem ipsum")  

So I have added belongs_to to the Notification model I've created, which you can see below:

class Notification < ActiveRecord::Base   belongs_to :project   validates :icon, presence: true   validates :text, presence: true, length: { maximum:75 }   validates :project_id, presence: true   enum status: {green: 1, orange: 2, red: 3, dark_grey: 4, light_grey:5}  end  

And added the has_many association to the Project model:

class Project < ActiveRecord::Base   belongs_to :user    has_many :notifcations   before_save :set_start_date   validates :name, presence: true, length: {maximum: 255}   validates :website, presence: true   WEBSITE_REGEX = /\A(?:(?:https?|http):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?\z/i   validates :website, format: { with: WEBSITE_REGEX }, if: 'website.present?'   validates :industry, presence: true   validates :user_id, presence: true  end  

But when I open de rails console and go enter the following:

project = Project.last  #returns project  project.notifications.build(icon: "icon.jpg", text: "lorem ipsum")  

I get the following error:

NoMethodError: undefined method `notifications' for #<Project:0x00000005916ef0>  Did you mean?  notifcations  

Wednesday, June 29, 2016

How can I repeat a POST request in Rails? | Fixed issues

How can I repeat a POST request in Rails? | Fixed issues


How can I repeat a POST request in Rails?

Posted: 29 Jun 2016 08:23 AM PDT

I have some error-handling code that sometimes needs to do some stuff and then re-try the current request. This works fine when it's a GET request, but not otherwise. In other words, I can't redirect_to request.path when request.post? is true.

Is there some way I can take the current request object, be it GET, POST, PATCH, or whatever, and just restart it?

Accessing value of select_tag in Controller

Posted: 29 Jun 2016 08:16 AM PDT

I am having trouble accessing a value of select_tag in my controller. I have the following select_tag in my view:

= select_tag "yessir", options_for_select([ ["No Teardown Time","0"],["15 Minutes", "15"], ["30 Minutes", "30"], ["45 Minutes", "45"], ["60 Minutes", "60"], ["75 Minutes", "75"], ["90 Minutes","90"], ["105 Minutes", "105"],["120 Minutes","120"]], @event.teardown_time), {:prompt => 'Teardown Time'}  

And I try to access it in my controller like such:

a = params["yessir"]  

I have also tried

a = params[:yessir]  

But in either case I keep on getting undefined local variable or method `params' for #. Any suggestions? Cheers~

Capistrano 3 does not restart my rails app after deployment

Posted: 29 Jun 2016 08:14 AM PDT

I use the following deploy.rb :

# config valid only for current version of Capistrano  lock '3.4.0'  set :application, '*****'  set :rails_env, 'production'  set :repo_url, 'admin@test.*******.***:/srv/outils/repos/*****'  set :scm, :git    namespace :deploy do      after :restart, :clear_cache do      on roles(:web), in: :groups, limit: 3, wait: 10 do        # Here we can do anything such as:        # within release_path do        #   execute :rake, 'cache:clear'        # end      end    end    #after 'deploy:publishing', 'deploy:restart'  end  after 'deploy:publishing', 'deploy:restart'  

It correctly deploy the app but does not restart it. What should i modify to make it restart? There is no message, error or otherwise, about the restart.

Creating rails cookie when force_ssl

Posted: 29 Jun 2016 08:14 AM PDT

There Rails project. It works on https (config.force_ssl = true) and is located on the subdomain.

Cookie I need on the primary domain and all its sub-domains, ssl only on where is created cookie.

So I create a cookie:

cookies.permanent[:my_uid] = {value: @ user.id, domain:: all, secure: false}  

And here is what my browser this cookie:

enter image description here

Due force_ssl: true ignored cookie flag secure: false. How to avoid it?

Rails instance object valivate

Posted: 29 Jun 2016 08:26 AM PDT

I was trying to practice Rspec, but seems I was confused about some rails part.

Here is Zombie.rb

class Zombie < ActiveRecord::Base      validates :name, presence: true      has_many :tweets      def hungry?          true      end  end  

It seems when I create a Zombie instance, it will check the name attribute. So, I wrote these Rspec code.

it 'should not be hungry after eating' do           @zombie = Zombie.create           @zombie.should_not be_valid          @zombie.hungry?.should be_truthy      end  

Why it will pass? If the @zombie is not valid, why @zombie.hungry? will still return true

MultiJson Oj as a default instead of json_pure in Rails 4?

Posted: 29 Jun 2016 08:08 AM PDT

Is there a way to force Rails 4.2.5 to use MultiJson with Oj by default?

I have it in Gemfile and running MultiJson.engine in the console shows MultiJson::Adapters::Oj.

But on one page I'm getting following error related to encoding and it is using json_pure instead of MultiJson:

/gems/ruby-2.3.1@report/gems/json_pure-1.8.3/lib/json/common.rb:223:in 'encode'

Rails partial for collection, only display certain things for first element

Posted: 29 Jun 2016 08:07 AM PDT

I have a collection of elements I'm rendering in a partial, but I only want to display a certain element with the very first element. My specific instance is displaying email addresses but I only want the email icon to show once next to the first instance (similar to how the Android Contacts app does).

I have a very "hacky" solution that uses instance variables in the view, which is not a good practice. But I'm struggling to find a cleaner way to implement what I want.

The controller:

@email_addresses = EmailAddress.order(:primary) # primary is a boolean value  

The partial:

# views/email_addresses/_email_address.html.erb  <div class="email-address">    <% unless @email_icon_displayed      <% @email_icon_displayed = true %>      <div class="email-address-icon">        <span class="icon email"></span>      </div>    <% end %>    <div class="email-address-value">      <%= email_address.value %>    </div>  </div>  

Calling partial in view:

<%= render partial: "email_addresses/email_address", collection: @email_addresses %>  

This works properly and only displays the email icon for the first element, but instance variables in the view seems like a bad idea.

I am getting following error while running diaspora pod (ruby application) deployed on ubuntu14.04 system

Posted: 29 Jun 2016 08:06 AM PDT

I am getting following error while running diaspora pod (ruby application) deployed on ubuntu14.04 system

bundler: failed to load command: unicorn (/home/ubuntu/.rvm/gems/ruby-2.1.8@diaspora/bin/unicorn)

Require an OS package in capistrano

Posted: 29 Jun 2016 08:13 AM PDT

I need to verify that an OS package is installed after deploying using capistrano (it's a rails project, in case it matters). I'd like to support the major linux distros and OS X. Fortunately, the name of the package is the same on all platforms.

I've thought adding a capistrano task, something like (untested code):

%w(yum apt-get brew).each do |manager|    path = `which #{manager}`.chomp    if path && path.size > 0      `#{path} install -y #{PKG}`      return    end  end  

Inspired by this question.

Is there a better way? I've thought checking uname, but it doesn't always have the distro, just "Linux". I also thought using lsb_release or listing files in /etc/*-release, but not all distros support it (e.g. centos).

Model evaluates to nil if declared within 'if' block

Posted: 29 Jun 2016 08:12 AM PDT

I have a rails app that has a model chart, and a chart has a datasource. A datasource may have many datapoints. In my chart create method I have the following line:

@chart = Chart.new(chart_params)  @chart.datasource = Datasource.find_by_id(2)  @chart.save  

This works fine - although it's not what I'm trying to do. What I'm trying to do is the following:

if @chart.id == 2        @chart.datasource = Datasource.find_by_id(2)        @chart.save  end  

When I do that, however, I get NoMethodError in Charts#show

undefined method 'datapoints' for nil:NilClass

The error in my Charts#show is generated starting with:

<% @chart.datasource.datapoints.each do |c| %>            dates.push( "<%= c.date %>" )            counts.push( <%= c.count %> )  <% end %>  

Remember, this works perfectly fine if I hard-code the datasource id outside of an if block, wondering what could be causing this.

Could not find compatible versions for gem "spree_core"

Posted: 29 Jun 2016 07:45 AM PDT

I've just ran through the 'Getting Started' guide from Spree commerce and I've hit an error while following it.

I've run the following commands:

gem install spree_cmd  bundle install  

Then I get hit with the following errors in the console

Bundler could not find compatible versions for gem "spree_core":    In Gemfile:      spree_auth_devise (~> 3.0.0) was resolved to 3.0.5, which depends on        spree_core (~> 3.0.0)        spree (~> 3.1.0) was resolved to 3.1.0, which depends on        spree_backend (= 3.1.0) was resolved to 3.1.0, which depends on          spree_core (= 3.1.0)        spree (~> 3.1.0) was resolved to 3.1.0, which depends on        spree_backend (= 3.1.0) was resolved to 3.1.0, which depends on          spree_core (= 3.1.0)        spree (~> 3.1.0) was resolved to 3.1.0, which depends on        spree_backend (= 3.1.0) was resolved to 3.1.0, which depends on          spree_core (= 3.1.0)        spree (~> 3.1.0) was resolved to 3.1.0, which depends on        spree_backend (= 3.1.0) was resolved to 3.1.0, which depends on          spree_core (= 3.1.0)        spree (~> 3.1.0) was resolved to 3.1.0, which depends on        spree_backend (= 3.1.0) was resolved to 3.1.0, which depends on          spree_core (= 3.1.0)  

Which looks like it all checks out - but it seems to be failing to bundle install.

My Gemfile

gem 'spree', '~> 3.1.0'  gem 'spree_gateway', '~> 3.0.0'  gem 'spree_auth_devise', '~> 3.0.0'  

Any help would be brilliant

Create model based on another model attributes Rails

Posted: 29 Jun 2016 07:44 AM PDT

Lets say i have 2 models Quote and Invoice and they share common fields. How do you convert a Quote to an Invoice. How would that work around the models and controllers with creating a new Invoice based on the values already stored in the Invoice?

Devise sign_in resource works even without importing module

Posted: 29 Jun 2016 07:39 AM PDT

So, I was customizing devise in a custom sign up page which required me to sign_in a user after creating the account along with some other operations. After creating the resource I did

sign_in resource if resource.active_for_authentication?  

and it signs in the user. My controller inherits the ApplicationController and I haven't included any modules like this

include Devise::Controllers::SignInOut  

How did rails know about the

sign_in  

method

Conflicting View Logic

Posted: 29 Jun 2016 07:56 AM PDT

I have a show page where I need to both show the student's units and create a unit for them. However an error is being incurred when trying to do both.

In my controller

def show    @student = Student.find(params[:id])    @unit = @student.units.build    @units = @student.units  end  

In my view

<%= simple_form_for @unit, url: student_units_path(@student) %>    # form...  <% end %>    <% @units.each do |unit| %>    <tr>      <td><%= unit.course %></td>      <td><%= unit.mailing_date.strftime('%m/%d/%y') %></td>    </tr>  <% end %>  

The unit.course call works and any call that is only the first child of unit, however when I call a second method on unit I get this error:

undefined method `strftime' for nil:NilClass  

despite knowing that the unit exists, hence the first call working

How can I proprerly use an instance variable in a link_to?

Posted: 29 Jun 2016 07:34 AM PDT

How can I resolve this ?

I had 2 buttons : /views/subjects/_inscription_button.html.haml

  - if subject.participation(current_participant).nil?      = link_to "Ca m'intéresse !",   subject_participant_index_path(:interested_id => current_participant.id, :subject_id => subject.id), remote: true, :method => :post, class:"btn btn-primary"      - else      = link_to "Ca ne m'intéresse plus !",   delete_participation_path(@subject.participation(current_participant).id),:method => :delete, remote: true, class:"btn btn-primary"  

The second link_to doesn't want to switch properly. I get the error :

NoMethodError at /subject_participant/115 undefined method `id' for nil:NilClass

The instance variable subject works for the first button but not the second...

Here is the rest of the usefull code : subject_participant_controller.rb :

class SubjectParticipantController < ApplicationController    before_action :authenticate_participant!        def create     @subject = Subject.find(params[:subject_id])     @subject_participant = SubjectParticipant.new(subject_participant_params)       if @subject_participant.save       respond_to do | format |        format.html {redirect_to subjects_path}        format.js       end     else      redirect_to subjects_path     end    end      def destroy      @subject_participant = SubjectParticipant.find(params[:id])      if @subject_participant.destroy       respond_to do | format |        format.html {redirect_to subjects_path}        format.js       end      else       redirect_to subjects_path      end    end      def subject_participant_params      params.permit(:interested_id, :subject_id, :id)    end  end  

/routes.rb :

Rails.application.routes.draw do   devise_for :participants   resources :subjects   resources :participants   resources :conferences   resources :subject_participant     delete 'subject_participant/:id' => 'subject_participant#destroy', as: 'delete_participation'   root 'welcome#index'  

subject.rb

class Subject < ActiveRecord::Base    validates_presence_of  :title, :questioner, :conference, :description      has_many :subject_participants    has_many :interested, through: :subject_participants #interested    belongs_to :questioner, class_name: "Participant"    belongs_to :conference      def participation(current_participant)      self.subject_participants.find_by_interested_id(current_participant.id)   end  end  

pg_search seems to ignore `using` for associated_against

Posted: 29 Jun 2016 07:37 AM PDT

I am trying to figure out why the using specifications does not works for the associated against fields. My code is:

 include PgSearch     pg_search_scope :search,      {        :associated_against => {         :client => [:name, :email],       },       :against => [:description],       using: {         tsearch: {},         trigram:    {threshold:  0.1}       }      }  

For field description it works well.

Any tips here ?

Thanks in advance.

How to setup a Ruby On Rails project in IntelliJ 2016? [on hold]

Posted: 29 Jun 2016 07:18 AM PDT

So i am just about to start learning web development by using the ruby on rails framework. I have installed the plugin for Ruby in the intelliJ plugin repository. How do i setup a rails project in IntelliJ 2016?

Rails cache Permission Denied when cache is very large

Posted: 29 Jun 2016 07:08 AM PDT

My app uses extensive rails caching, and all the cache keys are created and used by the same application, which has full rights to the cache folder.

However, occasionally when the cache gets particularly large (large uptick in use within the cache expiration window), I start getting permissions errors when accessing the cache fragments using Rails.cache.fetch:

Permission denied @ unlink_internal  

Clearing the cache "fixes" the problem, until it gets large again. Is there a theoretical limit to the size such a cache can be, or could there be some other cause?

Rails Active Record Omitting Where Clause

Posted: 29 Jun 2016 08:19 AM PDT

I have an Active Record query that sits inside of a gem. Database used is postgres.

Client.where(date:@date,client:@business_id)  

The gem uses a get request to pull this data. When there are too many values in @business_id, the URI is too long. Gem does not have post requests.

Workaround:

The business problem is when all the @business_id get passed to the app. I could have an "all" button, that triggers all the client values to show. I would need to ignore the client:@business_id part of the query.

How could I construct the query so that when all of the @business_id need to be passed, it ignores the client:@business_id part of the query?

Rails, Carrierwave, specifically :image parameter is not even being passed through POST

Posted: 29 Jun 2016 07:14 AM PDT

I am trying to save an :image to an article.

But my form sends ALL the other parameters but not the :image one.

My log:

Started POST "/articles/create" for 127.0.0.1 at 2016-06-29 16:56:59 +0300  Processing by ArticlesController#create as HTML    Parameters: {"utf8"=>"✓", "authenticity_token"=>"Neo/3LqX40cQKzlCwrK8cxYdkb6g95d1dbihCRtL5J8uIPZ5M7OOCbe+IWU9mwWK7dmqJy6s3G7uDXuvI2ZxiQ==", "article_type"=>"news", "article"=>{"strings"=>{"1"=>{"title"=>"sds", "text"=>"dsds"}}}}  

My form:

<%=form_for @article, url: articles_create_path, remote: true, authenticity_token: true, html: {class: "form-horizontal"} do |f|%>          <%= hidden_field_tag 'article_type', @articleType  %>          <fieldset class="content-group">          <%if !(@articleType=='notifs') %>            <legend class="text-bold">Image</legend>              <div class="form-group">              <div class="col-lg-10">                <%= f.file_field :image, :class => 'file-input-custom', 'data-show-caption' => true, 'data-show-upload' => false, :accept => 'image/*'%>              </div>            </div>            <% end %>          </fieldset>          <%= f.fields_for :strings do |fa| %>          <fieldset class="content-group">            <legend class="text-bold">Localization</legend>            <div class="tabbable">                <div class="tab-content">                <% @languages.each do |lang| %>                <%= fa.fields_for lang.id.to_s do |fb| %>                  <div class="tab-pane active" id="basic-justified-tab-<%= lang.id %>">                  <div class="form-group">                    <label class="col-lg-2 control-label text-semibold"><%= lang.name %> Title: <span class="text-danger">*</span></label>                    <div class="col-lg-10">                      <%= fb.text_field :title, :class => 'form-control', :required => 'required' %>                    </div>                  </div>                    <div class="form-group">                    <label for="title" class="col-md-4 col-md-offset-1"><%= lang.name %> Text:</label>                    <%= fb.text_area :text, :style => "height: 150px;", :class => 'wysihtml5 wysihtml5-min form-control', :required => 'required' %>                  </div>                </div>                <hr>                  <% end %>                <% end %>              </div>            </div>            </fieldset>          <% end %>                                          <div class="form-group">              <div class="col-md-2 col-md-offset-8">              <input type="submit" class="btn btn-success" value="Submit" >            </div>            </div>            <% end %>  

And my Articles controller:

class ArticlesController < ApplicationController      before_action :set_article, only: [:edit, :delete, :update, :destroy]        def new          @articleType = params[:article_type]          @article = Article.new          @languages = Language.all      end        def create            @article = Article.new(article_params)          @article.article_type = params[:article_type]            if @article.save && manage_strings              @status = 'success'          else              @status = 'error'              @errormessages = @article.errors.full_messages          end          respond_to do |format|              format.js          end      end        def edit                end        def update          @articleType = @article.article_type          if @article.update(article_params) && manage_strings              @status = 'success'          else              @status = 'error'              @errormessages = @article.errors.full_messages          end          byebug          respond_to do |format|                format.js          end      end        def delete_article          @article = Article.find(params[:id])          @articleType = @article.article_type          if @article.destroy              @status = 'success'          else              @status = 'error'              @errormessages = @article.errors.full_messages          end          respond_to do |format|              format.js          end      end        private            def article_params                if params[:article][:image].present?                  params.require(:article).permit(:id, )              else                  params.require(:article).permit(:id,:image)              end          end        def set_article          @article = Article.find_by_id(params[:id])            @languages = Language.all      end            def manage_strings          if params[:article][:strings].any?              params[:article][:strings].each do |key,value|                  string = @article.localizations.find_or_initialize_by(:language_id => key.to_i)                  string.title = params[:article][:strings][key][:title]                  string.text = params[:article][:strings][key][:text]                  string.save              end          end       end    end  

I have a string :image in my articles table and I do have

mount_uploader :image, ImageUploader

In my Articles

Can you find what am I doing wrong? Could it be something wrong with Carrierwave and should I try to use another similar gem?

Seed Database with Data for Each User

Posted: 29 Jun 2016 07:06 AM PDT

I am trying to figure out the best way to populate the database for each user. My end target is to have each user who has_many goals have a list of prepopulated goals when the user is created. The issue I see with seeding is that this will only create ONE set of goals for every user to "share" and not an individual set of goals for each user with the same initial data.

This is my current layout:

weekly_goals table

user_id  title  status  

User.rb

has_many :weekly_goals  

WeeklyGoal.rb

belongs_to :user    #List of all goals hardcoded in  

Am I going about this with the wrong thought process? Is there a better way to do what I'm asking? Thanks!

Ruby Workflow Issue During Migration

Posted: 29 Jun 2016 07:00 AM PDT

I am using Ruby Workflow in my ActiveRecords using Gem: Workflow

Existing Running Code contains:

  • I am having an ActiveRecord: X
  • I am having two Migrations already:
    • (Ref1) CreateX migration (which creates table X)
    • (Ref2) CreateInitialEntryInX migration (which creates one entry in table X)

New Changes:

  • Now I wanted to add workflow in ActiveRecord X, hence I did:
    • (Ref3) I added the workflow code in ActiveRecord Model X (mentioning :status as my workflow field)
    • (Ref4) AddStatusFieldToX migration (which adds :status field in table X)

Now when I run rake db:migrate after the changes, the (Ref2) breaks cos Migration looks for :status field as it is mentioned in ActiveRecord Model in the Workflow section, but :status field has not been added yet as migration (Ref4) has not executed yet.

Hence, all the builds fail when all migrations are run in sequence, Any solution to this? I do not want to resequence any of the migration or edit any old existing migrations.

Unable to autoload constant ProfileProjectsController

Posted: 29 Jun 2016 06:42 AM PDT

I am getting an error while visiting /project/my/tasks in Rails 5 as Unable to autoload constant ProfileProjectsController, expected /home/ubuntu/workspace/app/controllers/profile_projects_controller.rb to define it

controller code

class Project::ProfileProjectsController < ApplicationController    def index      if current_user        @projects = Project.where(user_id: current_user.id)        render 'profile_projects/index'      end    end  end  

Multiple rails forms on same page: clicking submit button per form always works in safari, sometimes works in firefox

Posted: 29 Jun 2016 08:06 AM PDT

On an index page I have a table with a bunch of listed items. Each <tr></tr> within the table's <tbody>not only lists each item, but also allows you to

  • update that item
  • click edit to take you to the edit screen for that item

Here is a picture:

Showing table

Within development in safari: I can successfully update each listed item and it all works just fine. However: when running my feature spec with capybara and selenium-webkit (which uses firefox):

  • It appears that capybara finds the submit button ok and even clicks it
  • But then nothing happens. For some reason the form appears to not be submitting when that update button is clicked.

To make things even more strange: in development mode while testing with firefox, clicking the update button works sometimes. Sometimes it doesn't work and I have to refresh the page, and then it works.

I tried putting a binding.pry in right before clicking the Update abc button in order to manually click the button at that step. I noticed that clicking the button manually was not submitting the form either.

Here is my relevant spec:

scenario "within the index page", js: true do    select 'some selection', from 'item_1_jazz'    select '12345', from 'item_1_something'    # I attempted putting a binding.pry here, and noticed that clicking the update button still wasn't submitting the form    find("#update_some_item_1_btn").click      expect(page).to have_content 'The item was successfully updated.'  end  

Update Here are my buttons within the form:

<td class="btn-group">    <%= f.submit 'Update abc', class: "btn btn-success btn-sm", id: "update_#{dom_id(item)}_btn" %>    <%= link_to edit_item_path(item), class: "btn btn-info btn-sm" do %>      <i class="fa fa-pencil"></i> Edit    <% end %>  </td>  

Question: In firefox: Capybara appears to find the submit button just fine and even click it. But why isn't Capybara able to submit the form within Firefox? Also: why in development mode with firefox does the button only work sometimes? It appears something is stopping the form form from submitting.

How to install and configure geckodriver on Rails / Ubuntu

Posted: 29 Jun 2016 06:09 AM PDT

I'm using Watir to scrape in production, but due to some firefox issues, it no longer is able to launch a browser (see here Watir Webdriver(0.9.1) No Longer Opens an Instance of Firefox).

Gecko driver is here: https://github.com/mozilla/geckodriver

How do I install geckodriver and configure rails to use it instead of the default firefox binary?

Thanks for any help.

Google Places gem error

Posted: 29 Jun 2016 06:13 AM PDT

I am trying to use the next page token from the first page results that are retrieved by the call to the Google Places, using the following code:

   def pins_in_area              @client = GooglePlaces::Client.new('api_key_XXXXX')              @results = @client.spots(params[:lat], params[:long], :radius => params[:radius])              puts @results              next_page_token = @results.last.nextpagetoken              puts next_page_token #spots_by_pagetoken              next_spots = @client.spots_by_pagetoken(next_page_token)              puts next_spots  

... end

But, I encounter the following error, not sure why:

Completed 500 Internal Server Error in 258ms (ActiveRecord: 0.0ms)    GooglePlaces::InvalidRequestError (GooglePlaces::InvalidRequestError):    app/controllers/api/v1/pins_controller.rb:89:in `pins_in_area'        Rendered /usr/local/rvm/gems/ruby-2.2.1/gems/actionpack-4.2.4/lib/action_dispatch/middleware/templates/rescues/_source.erb (13.1ms)    Rendered /usr/local/rvm/gems/ruby-2.2.1/gems/actionpack-4.2.4/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (35.1ms)    Rendered /usr/local/rvm/gems/ruby-2.2.1/gems/actionpack-4.2.4/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (2.0ms)    Rendered /usr/local/rvm/gems/ruby-2.2.1/gems/actionpack-4.2.4/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (101.1ms)  

l18n keep locale variable changing link rails

Posted: 29 Jun 2016 06:31 AM PDT

I am developing a rails application which must be in English or in Hungarian. The user may choose the language. So I use Rails Internationalization (I18n) API. The problem is that I do not understand how to keep the variable 'locale' when the user changes page.

#application_controller.rb  before_action :set_locale  def set_locale      I18n.locale = params[:locale] || I18n.default_locale  end  

Thanks a lot for your answers

foreman stop mina create current folder

Posted: 29 Jun 2016 06:09 AM PDT

Does someone know why the mina can't create the current directory after add foreman?

-----> Cleaning up old releases (keeping 5)
-----> Exporting foreman procfile for bash: line 152: cd: /home/ubuntu/test/current: File or directory not found sudo: bundle:
command not found ! ERROR: Deploy failed.
-----> Cleaning up build Unlinking current OK Connection to 55.77.221.43 closed.

deploy do      # Put things that will set up an empty directory into a fully set-up      # instance of your project.      invoke :'git:clone'      invoke :'deploy:link_shared_paths'      invoke :'bundle:install'      invoke :'rails:db_migrate'      invoke :'rails:assets_precompile'      invoke :'deploy:cleanup'      invoke :'foreman:export'          to :launch do        queue "mkdir -p #{deploy_to}/#{current_path}/tmp/"        queue "touch #{deploy_to}/#{current_path}/tmp/restart.txt"        invoke 'foreman:restart'      end  

How to convert human readable number to actual number in Ruby?

Posted: 29 Jun 2016 07:10 AM PDT

Is there a simple Rails/Ruby helper function to help you convert human readable numbers to actual numbers?

Such as:

1K => 1000    2M => 2,000,000    2.2K => 2200    1,500 => 1500    50 => 50    5.5M => 5500000  

how to draw pie chart in rails?

Posted: 29 Jun 2016 05:59 AM PDT

I have to models. Employee and locations . the association between them is location has many employees. and employee belongs to location. i want to draw a pie chart between this 2 models. means i want to show all locations and employees count of that location in pie chart. how can i do that?

i was trying to implement this using the Chartkick gem.

but do not know how to draw the graph between them.