Rails - 在link_to中动态切换确认消息

时间:2011-05-20 18:40:00

标签: ruby-on-rails ruby-on-rails-3 link-to confirm

我面对这种丑陋的重复,以便在我的视图中显示不同的确认信息。

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

2 个答案:

答案 0 :(得分: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/

答案 1 :(得分: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 %>