Show link only if association is present?

In my application, a Product has many subscriptions with the subscriber be a 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

How would I show the link block based on if the Product has a subscription or not?

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

Answers


i'll suggest to use method within User class

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

end

and for view use

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

Need Your Help

How do I Post Data in Android?

android http postdata

I've found this topic for PostData using http. but it doesn't work.

WCF REST Debugging

wcf debugging serialization

How can I log what xml is sent to my WCF REST service prior to being deserialized into my datacontract class?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.