2012-12-12 27 views
2

我試圖用康康來修改狂歡的管理/訂購網站。在我的商店裏,產品從不同的供應商處出售。註冊用戶有vendor_id,產品也有vendor_id。訂單下達後,訂單中的LineItemProduct,因此它有一個vendor_id與CanCan的狂歡訂單

我想要實現的是,當用戶登錄並訪問管理面板中的訂單頁面時,他只能看到訂購產品的訂單。用戶不應該看到來自其他供應商/用戶的其他訂單。

我試着用慘慘做到這一點通過設置一些能力:

def initialize(user) 
    if user.has_spree_role?("shop_manager") && !user.vendor.nil? 
     can :admin, Spree::Order 
     can :index, Spree::Order, :line_items => { :product => { :vendor_id => user.vendor_id } } 
     can :show, Spree::Order, :line_items => { :product => { :vendor_id => user.vendor_id } } 
     can :manage, Spree::LineItem, :product => { :vendor_id => user.vendor_id } 
     can :read, Spree::Order 
    end 
    end 

正如你所看到的,用戶應該只看到訂單在網站的首頁何處:line_items => { :product => { :vendor_id => user.vendor_id } }並且只應該看到LineItems哪裏:product => { :vendor_id => user.vendor_id }

但我得到的行爲是,我沒有被授權查看訂單的索引頁,並且每個LineItem都顯示在訂單的show操作中。

對於第二項任務,我認爲修改視圖是一個好主意。我試圖_order_details.html.erb從大禮包核心改變,改變顯示了所有LineItems循環:

<% @order.line_items.accessible_by(@current_ability).each do |item| %> 

但是這給了我一個Uninitialized constant Product(我想應該是Spree::Product)。所以,我不知道該怎麼辦,索引也不好,也不知道LineItems。希望有人有一個想法。

回答

1

爲什麼你同時設置限制:read,:show和:index?

:閱讀假設:索引和:顯示和任何別名的方法。

然後,如果您傳遞相關條件,則必須:加入或包含它。

def initialize(user) 
    if user.has_spree_role?("shop_manager") && !user.vendor.nil? 
    can :admin, Spree::Order 
    can :read, Spree::Order, Spree::Order.includes(:line_items).where(:line_items => { :product => { :vendor_id => user.vendor_id } }) 
    can :manage, Spree::LineItem, Spree::LineItem.includes(:product).where(:product => { :vendor_id => user.vendor_id }) 
    end 
end 

對於第二個問題,再試一次,但它會更好,如果你收集記錄之前運行的ActionView任何地方,在控制器。無論如何,它將快得多。

更新:

def initialize(user) 
    if user.has_spree_role?("shop_manager") && !user.vendor.nil? 
    can :admin, Spree::Order 
    can :read, Spree::Order, Spree::Order.includes(:line_items).where(:line_items => { :product => { :vendor_id => user.vendor_id } }) do |order| 
     order.line_items.includes(:product).exists?(:vendor_id => user.vendor_id) 
    end 
    can :manage, Spree::LineItem, Spree::LineItem.includes(:product).where(:product => { :vendor_id => user.vendor_id }) 
    end 
end 

什麼打發塊。當你定義:read時,第一個AR :: Relation語句過濾:index(列表),並且block子句過濾:show並且給你用戶可以的能力?並不能?

+0

THX你的答案。我必須分別處理'':index''和''read''方法,因爲spree會獨立處理它。我嘗試了上面的例子,並在訂單的顯示頁面上看到這個錯誤:''可以嗎?不能?調用不能與原始sql'can'定義一起使用。檢查代碼無法確定:show# 23tux

+0

嘗試通過該塊 –