[英]Rails 4 - checkboxes for has_and_belongs_to_many association
I recently had a problem getting checkboxes to work for a has_and_belongs_to_many (HABTM) association in Rails 4. I was able to find the information on how to get it working correctly in a few disparate places, but thought it would be good to document the few simple steps necessary to get it working correctly in one place here on StackOverflow. 我最近在Rails 4中获取has_and_belongs_to_many(HABTM)关联的复选框时遇到了问题。我能够找到有关如何在几个不同的地方使其正常工作的信息,但认为记录少数几个是好的在StackOverflow上的一个地方使它正常工作所需的简单步骤。
As a setup assume a model of Kennel with a HABTM association to Handler. 作为一个设置假设一个Kennel模型与HADTM关联到Handler。
class Kennel
has_and_belongs_to_many :handlers
end
This is all you need to do for the form: Don't do it manually when there is a built in helper. 这就是表单所需要做的全部内容:当有内置帮助程序时,不要手动执行此操作。
<%= form_for @kennel do |f| %>
<%= f.collection_check_boxes(:handler_ids, Handler.all, :id, :to_s) %>
<% end %>
The form should have something like this: 表单应该是这样的:
<%= form_for(@kennel) do |form| %>
...
<div class="field">
<div class="field_head">Handlers</div>
<%= hidden_field_tag("kennel[handler_ids][]", nil) %>
<% Handler.order(:name).each do |handler| %>
<label><%= check_box_tag("kennel[handler_ids][]", id, id.in?(@kennel.handlers.collect(&:id))) %> <%= handler.name %></label>
<% end %>
</div>
...
<% end %>
The hidden_field_tag allows the user to uncheck all the boxes and successfully remove all the associations. hidden_field_tag允许用户取消选中所有框并成功删除所有关联。
The controller needs to allow the parameter through strong parameters in the permitted_params method: 控制器需要通过allowed_params方法中的强参数允许参数:
params.permit(kennel: [:city, :state
{handler_ids: []},
:description, ...
])
References : 参考文献 :
I implement has_and_belongs_to_many
association this way: 我
has_and_belongs_to_many
这种方式实现has_and_belongs_to_many
关联:
model/role 模型/角色
class Role < ActiveRecord::Base
has_and_belongs_to_many :users
end
model/user 模型/用户
class User < ActiveRecord::Base
has_and_belongs_to_many :roles
end
users/_form.html.erb 用户/ _form.html.erb
---
----
-----
<div class="field">
<% for role in Role.all %>
<div>
<%= check_box_tag "user[role_ids][]", role.id, @user.roles.include?(role) %>
<%= role.name %>
</div>
<% end %>
</div>
users_controller.rb users_controller.rb
def user_params
params.require(:user).permit(:name, :email, { role_ids:[] })
end
Intermediate table_name should be roles_users and there should be two fields: 中间table_name应该是roles_users ,应该有两个字段:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.