我正尝试允许以简单的形式选择多个复选框字段:
<%= form_with(model: coffee_roast, local: true) do |form| %>
<% if coffee_roast.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(coffee_roast.errors.count, "error") %> prohibited this coffee_roast from being saved:</h2>
<ul>
<% coffee_roast.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<strong><%= form.label :name %></strong>
<%= form.text_field :name, id: :coffee_roast_name %>
</div>
<div class="field">
<strong><%= form.label :bean,"Select bean(s)" %></strong>
<%= collection_check_boxes(:coffee_roast, :coffee_beans, CoffeeBean.all, :id, :name) %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
collection_check_box通过连接表完美地从另一个模型中提取值。我的模型是:
coffee_bean.rb
class CoffeeBean < ApplicationRecord
has_many :coffee_blends
has_many :coffee_roasts, through: :coffee_blends
end
coffee_roast.rb
class CoffeeRoast < ApplicationRecord
belongs_to :roaster
has_many :coffee_blends
has_many :coffee_beans, through: :coffee_blends
has_many :flavours, through: :coffee_flavours
end
和联接表
coffee_blend.rb
class CoffeeBlend < ApplicationRecord
belongs_to :coffee_bean
belongs_to :coffee_roast
end
问题
当我保存coffee_roast
并选中几个复选框时,记录创建无误,但是在连接表中看不到任何ID。
我怀疑可能是由于不允许coffee_roast_controller.rb
我尝试了一些变体,但无法使其正常工作。这是我最近的尝试:
def coffee_roast_params
params.require(:coffee_roast).permit(:name, :coffee_bean_name, coffee_bean_id:[])
end
答案 0 :(得分:0)
尝试在下面喜欢
<%= f.collection_check_boxes :coffee_bean_ids, CoffeeBean.all.order(name: :asc), :id, :name do |cb| %>
<% cb.label(class: "checkbox-inline input_checkbox") {cb.check_box(class: "checkbox") + cb.text } %>
<% end %>
和控制器参数中
coffee_bean_ids:[]
代替coffee_bean_id:[]