1

我的 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>

我应该如何更正它以删除多余的逗号?

4

1 回答 1

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
于 2017-01-28T15:07:06.327 回答