嵌入式ruby表达式标记之间的逗号

时间:2017-01-28 14:56:52

标签: ruby-on-rails list comma embedded-ruby

我的rails应用程序包含一个供用户设置个人资料的表单。表单的一部分允许用户从长列表中选择服务,他们可以选择最多5种不同的服务。

<div class="form-group">
    <%= f.label :services_1 %>
    <%= f.select :services_1, ['Service 1', 'Service 2', 'Service 3', 'Service 4', 'Service 5', 'Service 6', 'Service 7', 'Service 8', 'Service 9', 'Service 9', ], {}, class: 'form-control' %>
  </div>
      
      <div class="form-group">
    <%= f.label :services_2 %>
    <%= f.select :services_2, ['Service 1', 'Service 2', 'Service 3', 'Service 4', 'Service 5', 'Service 6', 'Service 7', 'Service 8', 'Service 9', 'Service 9', ], {}, class: 'form-control' %>
  </div>
      
      <div class="form-group">
    <%= f.label :services_3 %>
    <%= f.select :services_3, ['Service 1', 'Service 2', 'Service 3', 'Service 4', 'Service 5', 'Service 6', 'Service 7', 'Service 8', 'Service 9', 'Service 9', ], {}, class: 'form-control' %>
  </div>
      
      <div class="form-group">
    <%= f.label :services_4 %>
    <%= f.select :services_4, ['Service 1', 'Service 2', 'Service 3', 'Service 4', 'Service 5', 'Service 6', 'Service 7', 'Service 8', 'Service 9', 'Service 9', ], {}, class: 'form-control' %>
  </div>
      
      <div class="form-group">
    <%= f.label :services_5 %>
    <%= f.select :services_5, ['Service 1', 'Service 2', 'Service 3', 'Service 4', 'Service 5', 'Service 6', 'Service 7', 'Service 8', 'Service 9', 'Service 9', ], {}, class: 'form-control' %>
  </div>

我想在他们的个人资料页面上列出这些

Service 1, Service 2, Service 3, Service 4, Service 5

但是,如果用户选择少于5个服务,例如只有2个,则会产生此

Service 1, Service 2, , ,

以下是我在视图文件中包含的内容

<p><%= @user.profile.services_1 %>, <%= @user.profile.services_2 %>, <%= @user.profile.services_3 %>, <%= @user.profile.services_4 %>, <%= @user.profile.services_5 %></p>

如何纠正它以删除多余的逗号?

1 个答案:

答案 0 :(得分:0)

我认为您希望将所选服务收集到一个数组中,然后将它们组合起来。

# in the controller
@services = []
@services << @user.profile.services_1 if @user.profile.services_1
@services << @user.profile.services_2 if @user.profile.services_2
@services << @user.profile.services_3 if @user.profile.services_3
@services << @user.profile.services_4 if @user.profile.services_4
@services << @user.profile.services_5 if @user.profile.services_5

# in the view
<p><%= @services.join(', ') %></p>

如果您不能将此登录简化为此,那么将此登录信息放在模型中也可能更好。

# in the model
def selected_services
  services = []
  services << services_1 if services_1.present?
  services << services_2 if services_2.present?
  services << services_3 if services_3.present?
  services << services_4 if services_4.present?
  services << services_5 if services_5.present?
  services
end

# in the controller
@services = @user.profile.selected_services