rails 4 has_many:通过不保存关联

我有2个模型,有多对多关联如下:

class User  :destroy has_many :designated_remarks, :through => :remark_users, :source => :remark end class Remark  :destroy has_many :users, :through => :remark_users accepts_nested_attributes_for :users end 

和关系:

 class RemarkUser < ActiveRecord::Base belongs_to :remark belongs_to :user end 

应该执行save的remarks_controller操作:

 # PATCH Save users def save_users @remark = Remark.find(params[:id]) @remark.users.build(params[:remark_user_ids]) @remark.save end 

forms:

  salveaza_responsabili_remark_path(@remark) do |f| %>       

Te remarks_controller:

 params.require(:remark).permit(:description, :suggestion, :origin_details, process_type_id, :origin_id, :remark_user_ids) 

用户和备注都已存在,我需要一个表单来创建关联,最好使用复选框。

在控制台中,将保存关联。 但我花了最后一天试图让它在浏览器中运行。 我已经阅读了所有关于此事的内容,我现在很困惑。

有人能指出我的实际forms是什么样的,如果需要在控制器中添加其他东西吗?

您的表单没有任何问题,但可以简化为以下内容

 <%= 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]的数组

 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