2012-04-07 74 views
0

在我的應用程序,一個Product有許多subscriptions與用戶是User僅當關聯存在時才顯示鏈接?

class User 
    has_many :products 
    has_many :subscriptions, :foreign_key => :subscriber_id 
end 

class Product 
    belongs_to :store 
    has_many :subscriptions, :as => :subscribable 
end 

class Subscription 
    belongs_to :subscriber, :class_name => "User" 
    belongs_to :subscribable, :polymorphic => true 
end 

我怎麼會顯示是否該產品已訂閱或不基於鏈接塊?

<% if #@product.subscription.present? %> 
    <%= link_to "Unsubscribe", { :controller => "products", :action => "unsubscribe_product", :id => product.id }, :method => :delete %> 
<% else %> 
    <%= link_to "Subscribe", { :controller => "products", :action => "subscribe_product", :id => product.id }, :method => :post %> 
<% end %> 

回答

2

我會建議用戶類

class User 
    def subscribed_for?(subscribable) 
    subscriptions.where(:subscribable_id => subscribable.id, :subscribable_type => subscribable.type).any? 
    end 

end 

內和視圖使用使用方法

<% if current_user.subscribed_for?(product) %> 
    <%= link_to "Unsubscribe", { :controller => "products", :action => "unsubscribe_product", :id => product.id }, :method => :delete %> 
<% else %> 
    <%= link_to "Subscribe", { :controller => "products", :action => "subscribe_product", :id => product.id }, :method => :post %> 
<% end %> 
相關問題