xps15z
xps15z

Reputation: 1829

Writing else statements in the views

How can I write in the view that will show content if the conditions are met? For example show a link to upgrade subscription if the users plan_id is 1, and then show a downgrade subscription link if the users plan_id is 12.

One of the links are <%= link_to "Upgrade to 12 months", subscriptions_updatesubscription_path, :data => { :confirm => "Are you sure?" } %>

Upvotes: 0

Views: 35

Answers (1)

vee
vee

Reputation: 38645

Something like this should work:

<% if user.plan_id == 1 %>
  <%= link_to "Upgrade to 12 months", subscriptions_updatesubscription_path, :data => { :confirm => "Are you sure?" } %>

<% elsif user.plan_id == 12 %>
  <%= link_to "Downgrade link", subscriptions_updatesubscription_path, :data => { :confirm => "Are you sure?" } %>
<% end %>

If this is frequently used, you could move this to a helper method and have it return appropriate link_to (as an example put in SubscriptionHelper below):

# app/helpers/subscription_helper.rb
module SubscriptionHelper
  def update_susbscription_link(plan_id)
    case plan_id 
    when 1
      link_label = 'Upgrade to 12 months'
    when 12
      link_label = 'Downgrade link'
    end

    link_to link_label, subscriptions_updatesubscription_path, :data => { :confirm => "Are you sure?" }
  end
end

Then in your view:

<%= update_subscription_link(user.plan_id) %>

Upvotes: 2

Related Questions