与Cancan嵌套关联混淆

时间:2014-07-09 12:11:13

标签: ruby-on-rails cancan

我试图为嵌套资源设置Cancan授权,但我似乎无法正常使用它。

我的系统设置如下

    class Listing
      has_many :listing_openings

    class ListingOpening
      belongs_to :listing

    class ListingOpeningsController < ApplicationController
      before_filter :authenticate_user! #checks user is logged in
      load_and_authorize_resource :listing
      load_and_authorize_resource :listing_opening, :through => :listing #as per cancan docs for nested resources

    ability.rb
      can [ :index, :create ], ListingOpening, :listing => { :user_id => user.id } #user must own listing
      can [ :update ], ListingOpening, :listing => { :user_id => user.id }

    routes.rb
      resources :listings, :except => [ :destroy ] do
        resources :listing_openings, :except => [ :destroy, :show ]
      end

要编辑开口,路径为/ listings / 800 / listing_openings / 7 / edit。 Cancan正确地检查列表800是否由当前用户拥有并将其作为@listing返回,并且说“未授权”&#39;除此以外。但是,它并没有检查开放ID 7是否属于列表800.它没有说“未授权”,而是提出了一个“ActiveRecord :: RecordNotFound”#39;我尝试输入无效的开放ID时出错。在某种程度上,这是有效的,但肯定它应该给出相同的错误,就像我试图编辑我不拥有的列表。 Cancan正在生成3个查询,看起来像这样

    Listing Load (0.7ms)  SELECT "listings".* FROM "listings" WHERE "listings"."id" = $1 LIMIT 1  [["id", "800"]]
    ListingOpening Load (0.5ms)  SELECT "listing_openings".* FROM "listing_openings" WHERE "listing_openings"."listing_id" = $1 AND "listing_openings"."id" = $2 LIMIT 1  [["listing_id", 800], ["id", "7"]]
    Listing Load (1.6ms)  SELECT "listings".* FROM "listings" WHERE "listings"."id" = $1 ORDER BY "listings"."id" ASC LIMIT 1  [["id", 800]]

最好的方法是什么 - 它应该只需要2个查询。我是在正确的轨道上吗?

0 个答案:

没有答案