是否可以避免代码重复?

时间:2015-04-08 21:05:40

标签: ruby-on-rails

如果找到邀请,用户不得指定电子邮件。我这样做了,对吧?

是否可以避免代码重复?

<% if @invitation %>
  <%= f.email_field :email, class: 'form-control', placeholder: t('.placeholder.email'), value: @invitation.email %>
<% else %>
  <%= f.email_field :email, autofocus: true, class: 'form-control', placeholder: t('.placeholder.email') %>
<% end %>

2 个答案:

答案 0 :(得分:2)

你可以在没有条件的情况下这样做:

f.email_field :email, class: 'form-control', placeholder: t('.placeholder.email'), value: @invitation && @invitation.email, autofocus: !@invitation

答案 1 :(得分:1)

有点难以阅读,但您可以合并您的选项:

<% f.email_field(:email, {class: 'form-control', placeholder: t('.placeholder.email')}.merge(@invitation ? {value: @invitation.email} : {autofocus: true})) %>