2014-03-26 49 views
0

如何在視圖中編寫將顯示滿足條件的內容的視圖?例如顯示一個鏈接升級訂閱如果用戶plan_id的數據類型爲1,然後顯示一個降級的訂閱鏈接,如果用戶plan_id的數據類型爲12在視圖中寫入else語句

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

回答

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) %> 
+0

謝謝,按預期工作。 – xps15z