Ruby on rails 嵌套表单:更新子外键

Ruby on rails 嵌套表单:更新子外键,ruby-on-rails,ruby-on-rails-4,activerecord,nested-forms,nested-attributes,Ruby On Rails,Ruby On Rails 4,Activerecord,Nested Forms,Nested Attributes,我有一个嵌套的关联: class User < ActiveRecord::Base has_many :hostels accepts_nested_attributes_for :hostels end class Hostel < ActiveRecord::Base belongs_to :user end 我想通过更新hotel外键将现有的hotels记录重新链接到新用户。这样,它肯定不起作用 已尝试仅更新\u:也将true参数更新为嵌套 关于这个主题有什么

我有一个嵌套的关联:

class User < ActiveRecord::Base
  has_many :hostels
  accepts_nested_attributes_for :hostels
end

class Hostel < ActiveRecord::Base
  belongs_to :user
end
我想通过更新hotel外键将现有的hotels记录重新链接到新用户。这样,它肯定不起作用

已尝试仅更新\u:也将true参数更新为嵌套


关于这个主题有什么想法吗?或者我完全错误地尝试这样做了吗?

您可以在表单中使用多个酒店选择,然后在控制器中您必须需要酒店ID

型号:

class User < ActiveRecord::Base
  has_many :hostels
end

class Hostel < ActiveRecord::Base
  belongs_to :user
end

我没有测试代码,但必须很好地工作。

我想我应该指出,大多数人不希望将本例中的所有模型都放入HTML中。主要是出于性能和安全原因。
def create
  @user = User.new(user_params)
  raise @user.hostels.inspect
end

private
def user_params
  params.require(:user).permit(:email, hostels_attributes: [:id])
end
class User < ActiveRecord::Base
  has_many :hostels
end

class Hostel < ActiveRecord::Base
  belongs_to :user
end
<%= form_for @user do |f| %>
 <%= f.label :email %><br>
 <%= f.text_field :email %>
 <%= f.label "Hostels" %><br>
 <%= select_tag :hotel_ids, options_for_select(Hostel.all.map{|h| [h.name, h.id]}), { :multiple => true } %>
 <%= f.submit %>
<% end %>
def create
  @user = User.new(user_params)
end

private
def user_params
  params.require(:user).permit(:email, hostel_ids)
end