2011-05-20 33 views
1

爲了在我的視圖中顯示不同的確認消息,我正面臨這個醜陋的重複。導軌 - 在鏈接中動態切換確認消息

<% if current_user.password.nil? and current_user.services.count == 1 %> 
    <%= link_to "Disconnect #{service.provider.capitalize}", service, :confirm => 'Remove this service will delete your account, are you sure?', :method => :delete %> 
<% else %> 
    <%= link_to "Disconnect #{service.provider.capitalize}", service, :confirm => 'Are you sure you want to remove this authentication option?', :method => :delete %> 
<% end %> 

我很高興知道是否有辦法避免這種情況?

謝謝!

編輯:

ActionView::Template::Error (/Users/benoit/rails_projects/website/app/views/services/index.html.erb:15: syntax error, unexpected ',', expecting ')' 
...e this authentication option?', :method => :delete, :class =... 
...        ^): 
    12:   <% for service in @services %> 
    13:   <div class="service"> 
    14:    <%= image_tag "logo_#{service.provider}.png", :class => "left" %> 
    15: <%= link_to "Disconnect #{service.provider.capitalize}", service, :confirm => current_user.password.nil? and current_user.services.count == 1 ? 'Remove this service will delete your account, are you sure?' : 'Are you sure you want to remove this authentication option?', :method => :delete, :class => "remove" %> 
    16: 
    17:    <div class="clear"></div> 
    18:   </div> 

回答

4

只需執行:

<%= link_to "Disconnect #{service.provider.capitalize}", service, :confirm => current_user.password.nil? and current_user.services.count == 1 ? 'Remove this service will delete your account, are you sure?' : 'Are you sure you want to remove this authentication option?', :method => :delete, :class => "remove" %> 

或者,如果你這是更容易理解:

<% confirm_message = current_user.password.nil? and current_user.services.count == 1 ? 'Remove this service will delete your account, are you sure?' : 'Are you sure you want to remove this authentication option?' %> 

<%= link_to "Disconnect #{service.provider.capitalize}", service, :confirm => confirm_message, :method => :delete, :class => "remove" %> 

我使用Ruby的三元運算符,檢查一下: http://invisibleblocks.wordpress.com/2007/06/11/rubys-other-ternary-operator/

+0

謝謝!然而,我得到這個:語法錯誤,意外',',期待')'...這個身份驗證選項?',:方法=>:刪除,試圖實現它 – benoitr 2011-05-20 18:55:48

+0

如果可能的話,你可以粘貼完整的代碼行號,和完整的堆棧跟蹤? – ronnieonrails 2011-05-20 18:58:47

+0

是的,我會編輯我的文章,在一分鐘內給你這個(謝謝) – benoitr 2011-05-20 19:03:40

3

你可以做一個輔助函數:

def auth_confirm_delete(current_user) 
    if current_user.password.nil? and current_user.services.count == 1 
     'Remove this service will delete your account, are you sure?' 
    else 
     'Are you sure you want to remove this authentication option?' 
    end 
end 

,然後它會在視圖更好:

<%= link_to "Disconnect #{service.provider.capitalize}", service, :confirm => auth_confirm_delete, :method => :delete %>