在我的应用中,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 %>
答案 0 :(得分:2)
我建议在User class
中使用方法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 %>