【问题标题】:nested forms : update child foreign key嵌套形式:更新子外键
【发布时间】:2014-12-21 14:31:54
【问题描述】:

我有一个嵌套关联:

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

class Hostel < ActiveRecord::Base
  belongs_to :user
end

形式:

<%= form_for @user do |f| %>
<%= f.label :email %><br>
<%= f.text_field :email %>
<% f.object.hostels << @hostel -%>
<%= f.fields_for :hostels do |ff| %>
<%= ff.hidden_field :id %>
<% end -%>
<%= f.submit %>
<% end -%>

控制器

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

我想通过更新旅馆外键将旅馆的现有记录重新链接到新用户。这样一来,肯定行不通。

也尝试将update_only: true 参数嵌套。

关于这个主题的任何想法还是我完全错误地尝试进行这样的操作?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 activerecord nested-forms nested-attributes


    【解决方案1】:

    您可以在表单中为酒店使用多项选择,然后在控制器中您必须要求 hostel_ids。

    型号:

    class User < ActiveRecord::Base
      has_many :hostels
    end
    
    class Hostel < ActiveRecord::Base
      belongs_to :user
    end
    

    Form:其中 :name 是您在多选中看到的内容

    <%= 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
    

    我没有测试代码,但一定能正常工作。

    【讨论】:

    • 我想我应该指出,大多数人不想将所有模型(在这种情况下为旅馆)放入他们的 HTML 中。主要是出于性能和安全原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-26
    相关资源
    最近更新 更多