I have the following:
User has_many Listings
Listing has_many Offers
Pretty basic. A user can publish listings and other users can make offers on those listings.
On each Listing View, you can see a description of the listing, and also a list of all of the offers it has received. Also, on this same view, there is a form which lets users make an offer on this Listing.
Of course, if I am looking at my own Listing, I do not want to be able to make an Offer. So, I'm trying to add a restriction on the Offer's create method, to only allow access to it if it is from a User different from the one that posted this Listing. In my Ability class, it would be something like:
can :create, Offer if listing.user != user
This doesn't work since listing
is not defined anywhere. This method will be called when a use开发者_运维百科r is viewing a certain listing
, so, how can I pass this current Listing to the cancan method to effectively check this restriction?
Thanks.
Move the CanCan ability check until after the point at which you've created the new offer. E.g.
#listing.rb
load_and_authorize_resource :except => :create
def create
@offer = #whatever it is you want to do
authorize! :create, @offer
end
精彩评论