Question

I have some simple actions which I want to call via js but got strange error, here is my code:

Controller:

class Admin::CEventsController < Admin::BaseController
  def add_speaker
    # speakers = session[:speakers] ? [] : session[:speakers]
    # speakers << Partner.find(params[:id])
    # session[:speakers] << speakers.uniq
    # @speakers = Partner.find(session[:speakers])
    # puts @speakers.inspect
  end

  def remove_speaker
    # speakers = session[:speakers]
    # speakers.destroy(params[:id])
    # session[:speakers] = speakers
    # @speakers = Partner.find(session[:speakers])
  end
end

Routes:

resources :c_events,         :except => [:show] do
      member do
        post :add_speaker
        post :remove_speaker
      end
    end

View:

<div class="row">
  <div class="small-6 columns">
    <% speakers.each do |p| %>
      <p><%= link_to p.name remove_speaker_admin_c_event_path(p), :method => :post, :remote => true %></p>
    <% end %>
  </div>

  <div class="small-6 columns">
    <% Partner.all.each do |p| %>
      <p><%= link_to p.name, add_speaker_admin_c_event_path(p), :method => :post, :remote => true %></p>
    <% end %>
  </div>
</div>

I commented some of actions code just to try to find the problem. The error I got is:

Started POST "/admin/c_events/2/add_speaker" for 127.0.0.1 at 2014-01-06 21:38:25 +0200 Processing by Admin::CEventsController#add_speaker as JS Parameters: {"id"=>"2"}
CEvent Load (0.1ms) SELECT "c_events".* FROM "c_events" WHERE "c_events"."id" = ? LIMIT 1 [["id", "2"]] Completed 404 Not Found in 12ms

ActiveRecord::RecordNotFound (Couldn't find CEvent with id=2):

Seems like another actions is called, another actions in this controller is standard CRUD rails acctions

Was it helpful?

Solution

This is a partial answer because I don't know precisely how to solve your problem, but I can at least tell you where it is and hopefully give you an idea so you can figure out the rest.

Based on the stacktrace, it looks like you're using the CanCan gem. Apparently, it is intercepting the request before it gets to your action, as evidenced by this portion of the stacktrace:

...
activerecord (3.2.14) lib/active_record/querying.rb:5:in `find'
cancan (1.6.10) lib/cancan/model_adapters/abstract_adapter.rb:20:in `find'<- here
cancan (1.6.10) lib/cancan/controller_resource.rb:116:in `find_resource'
...

Unfortunately, I am not familiar with this library. However, after browsing their wiki page, I was able to find this information regarding conditionally checking authorization.

According to that page, you might be able to get away with something like this:

skip_authorization_check :only => [:add_speaker, :remove_speaker]

I assume doing this will suppress CanCan's authorization check, thus preventing your error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top