0

在我的应用程序中, a与订阅者Product有很多是 a :subscriptionsUser

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 %>
4

1 回答 1

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 %>
于 2012-04-07T18:18:17.397 回答