Cancan doesn't always show authorized link
I'm using Cancan to control User
abilities, and have recently run into an odd issue: my partial has a "destroy" hyperlink that shows up only sometimes for authorized users. When I refresh the page, there's no telling whether the link will exist or not.
I've defined abilities for my Event
model in Ability.rb
in the following way:
can [:create, :update, :destroy], Event do |event|
user.regattas(true).include?(event.regatta)
end
I use regattas(true)
to prevent the system from using the cached associations, in case something's changed recently.
In my rspec tests, this works great for the current user, both in my tests for Ability.rb
and my EventsController
tests.
Here's the destroy. destroy hyperlink in my _event.html.erb
partial, that I only want to appear when the user has the ability to destroy event
:
<% if can? :destroy, event %>
<td><%= link_to 'Destroy', event, :confirm => 'Are you sure?', :method => :delete %></td>
<% end %>
Any advice for how fix the flickering, and get the "Destroy" link to ALWAYS show up for authorized users? Has anyone else run into this issue?
More background: I don't have this issue for another piece of code, not in a partial, shown here:
<% if can? :update, @regatta %>
开发者_JS百科 <%= link_to 'Edit Regatta Info', edit_regatta_path(@regatta) %> |
<% end %>
Thanks, all.
Ryan Bates actually answered this one for me, on this cancan github issue. Looks like Cancan has a known issue with models using default_scope
, documented on this ticket. In my case, event.rb
included a call to default_scope
. Taking that line out completely fixed the issue.
The discussion on the second ticket indicated that this was an issue with Ruby on Rails, as discussed in this lighthouse ticket.
Hope this helps anyone else with this strange issue! Thanks, Ryan... I'll switch the answer over to you, if you happen to post on this.
精彩评论