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 make svnant/svnkit prompt for a username/password

svn ant svnkit svnant

I have an Ant script that needs to checkout a directory from Subversion. This works using svnant/svnkit. However, Subversion access is authenticated, and I do not want to store my user password in ...

Repeating Header in a group

.net regex

I am parsing text that has a heading and then data that applies to that heading. I need to break each data field into groups, and have the heading also apply to those groups. Here's an example: