轨道简单形式不从输入传递参数



我想显示一个InvestorTypes列表(作为单选按钮(,但在每个类型之前,我应该能够添加该类型的解释。这是我得到的:

<%= simple_form_for(resource, as: resource_name, url: users_user_experience_level_path(resource_name), html: { method: :put }) do |f| %>
<div class="form-inputs">
<% User::USER_EXPERIENCE_LEVEL.each do |level| %>
<b>Investor type <%= level %></b>
<%= t("user.description.#{level}") %>
<%= f.input :experience_level, collection: [level], as: :radio_buttons, label: false %>
<% end %>
</div>
<div class="form-actions">
<%= f.button :submit, 'Submit' %>
</div>
<% end %>

这给了我预期的观点:

Investor type Beginner
Some explanation of what is going on
[checkobox] type Beginner
Investor type Expert
Some clarification of who is an expert and what ever you want to display here
[checkbox] type Expert
Investor type Institutional
Some clarification of who is an institutional client and some legal stuff
[checkbox] type Institutional

但当按下提交按钮时,它不会将输入值(用户选择的单选框选择(传递到参数:

=> #<ActionController::Parameters {"experience_level"=>""} permitted: true>

[编辑]

class User < ApplicationRecord
USER_EXPERIENCE_LEVEL = %w[institutional beginner expert].freeze
end

在我看来,你用错了简单的形式。";集合";SimpleForm中的输入期望得到一个完整的选项列表,而不仅仅是一个选项。

循环的方式是为每个体验级别创建一个组,每个组中只有一个按钮。因此,它在视觉上看起来可能是正确的,但它并没有按照你想要的方式运行。相反,您希望为体验级别创建一组单选按钮,这样每个按钮都会更改体验级别的值。

因为您在外观方面进行了大量的自定义,所以这可能不是SimpleForm的一个好用途,相反,您应该回到普通的Rails表单助手。

您想将一个块传递给f.input以获得简单的表单包装器,然后使用较低级别的rails助手:

<%= simple_form_for(resource, as: resource_name, url: users_user_experience_level_path(resource_name), html: { method: :put }) do |f| %>
<div class="form-inputs">
# adds the simple form wrapper 
<%= f.input :experience_level do %>
# iterates across the options and yields a input builder to each iteration
<%= f.collection_checkboxes(:experience_level, User::USER_EXPERIENCE_LEVEL, :value_method, :label_method) do |cb| %>
# There are three special methods available: 
# object, text and value, 
# which are the current item being rendered, its text and value methods, respectively.
<%= t("user.description.#{cb.text}") %>
<%= cb.check_box %>
<% end %>
<% end %> 
</div>
<div class="form-actions">
<%= f.button :submit, 'Submit' %>
</div>
<% end %>

如果你实际上没有一个模型,你可以使用#itself在一个平面数组中迭代:

<%= f.collection_checkboxes(:experience_level, User::USER_EXPERIENCE_LEVEL, :itself, :itself) do |cb| %>

或者一组配对:

<%= f.collection_checkboxes(:experience_level, User::USER_EXPERIENCE_LEVEL.zip(User::USER_EXPERIENCE_LEVEL), :first, :last) do |cb| %>

甚至是一个结构。

最新更新