仅在存在关联时才显示链接?

时间:2012-04-07 18:03:49

标签: ruby-on-rails ruby-on-rails-3

在我的应用中,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 %>

1 个答案:

答案 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 %>