在视图中编写else语句

时间:2014-03-26 17:28:55

标签: ruby-on-rails

如果符合条件,我如何在视图中写入内容?例如,如果用户plan_id为1,则显示升级订阅的链接,如果用户plan_id为12,则显示降级订阅链接。

其中一个链接是<%= link_to "Upgrade to 12 months", subscriptions_updatesubscription_path, :data => { :confirm => "Are you sure?" } %>

1 个答案:

答案 0 :(得分:2)

这样的事情应该有效:

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

如果经常使用此方法,您可以将其移至辅助方法并让其返回适当的link_to(作为下面SubscriptionHelper中的示例):

# 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

然后在你看来:

<%= update_subscription_link(user.plan_id) %>