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  

No comments:

Post a Comment