问题描述
我有2个模型,它们之间具有多对多关联:
I have 2 models with many to many association as follows:
class User < ActiveRecord::Base
has_many :remark_users, :dependent => :destroy
has_many :designated_remarks, :through => :remark_users, :source => :remark
end
class Remark < ActiveRecord::Base
has_many :remark_users, :dependent => :destroy
has_many :users, :through => :remark_users
accepts_nested_attributes_for :users
end
与关系:
class RemarkUser < ActiveRecord::Base
belongs_to :remark
belongs_to :user
end
应该执行保存的remarks_controller动作:
The remarks_controller action that should do the save:
# PATCH Save users
def save_users
@remark = Remark.find(params[:id])
@remark.users.build(params[:remark_user_ids])
@remark.save
end
表格:
<%= form_for @remark, :url => salveaza_responsabili_remark_path(@remark) do |f| %>
<% @users.each do |user| %>
<%= check_box_tag 'remark[remark_user_ids][]', user.id, @remark.users.include?(user) %>
<%= user.name %>
<% end %>
<%= hidden_field_tag 'remark[remark_user_ids][]', '' %>
<% end %>
Te备注控制器:
params.require(:remark).permit(:description, :suggestion, :origin_details, process_type_id, :origin_id, :remark_user_ids)
用户和备注都已经存在,我需要一个仅用于创建关联的表格,最好使用复选框.
Both the User and the Remark already exists, I need a form just for creating the associations, preferably using check boxes.
在控制台中,关联已保存.但是我花了最后一天试图使其在浏览器中运行.我已经阅读了所有关于此事的资料,现在我很困惑.
In Console, the association is saved. But I spend last day trying to make it work in the browser. I have read all what I could find on this matter, and I am very confused right now.
有人可以指出实际形式是什么,以及是否需要在控制器中添加其他内容吗?
Can someone point me on what the actual form would have to look like, and if there is need to add anything else in the controller?
推荐答案
您的表单没有错,但是可以简化为以下形式
There's nothing wrong with your form but it can be simplified to the following
<%= form_for @remark, :url => salveaza_responsabili_remark_path(@remark) do |f| %>
<% @users.each do |user| %>
<%= check_box_tag 'user_ids[]', user.id, @remark.users.include?(user) %>
<%= user.name %>
<% end %>
<% end %>
然后在控制器中,可以从params[:user_ids]
Then in your controller, you can expect an array from params[:user_ids]
def save_users
@remark = Remark.find(params[:id])
# This is where you need to think about things. If the checkbox in the form
# contains all the users for a remark, the following code should work.
#
# @remark.user_ids = params[:user_ids]
# @remark.save
#
# otherwise, you have to loop through each user_id
params[:user_ids].each do |user_id|
@remark.remark_users.create!(user_id: user_id)
end
end
这篇关于rails 4 has_many:通过不保存关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!