accepts_nested_attributes_for是否适用于belongs_to?

Nic*_*k M 58 belongs-to nested-attributes ruby-on-rails-3

关于这个基本问题我得到了各种相互矛盾的信息,答案对我目前的问题非常关键.因此,非常简单,在Rails 3中,允许或不允许将accepts_nested_attributes_for与belongs_to关系一起使用吗?

class User < ActiveRecord::Base
  belongs_to :organization
  accepts_nested_attributes_for :organization
end

class Organization < ActiveRecord::Base
  has_many :users
end
Run Code Online (Sandbox Code Playgroud)

在一个视图中:

= form_for @user do |f|
  f.label :name, "Name"
  f.input :name

  = f.fields_for :organization do |o|
    o.label :city, "City"
    o.input :city

  f.submit "Submit"
Run Code Online (Sandbox Code Playgroud)

kid*_*rew 22

从Rails 4开始,嵌套属性似乎适用于belongs_to关联.它可能在早期版本的Rails中已经更改,但我在4.0.4中测试过,它肯定能按预期工作.

  • 仍然在Rails 4.1.1中,accepts_nested_attributes不适用于*polymorphic*belongs_to.我不得不把它移到协会的另一边(has_one).这只是为了与他人分享信息. (11认同)

rob*_*rty 21

doc epochwolf在第一行中引用了状态"嵌套属性允许您通过父级保存关联记录的属性." (我的重点).

您可能对这个此问题相同的其他SO问题感兴趣.它描述了两种可能的解决方案:1)将accepts_nested_attributes移动到关系的另一端(在本例中为Organization),或2)使用该build方法在呈现表单之前在User中构建Organization.

我还找到了一个要点,它描述如果你愿意处理一些额外的代码,可以使用belongs_to关系使用accepts_nested_attributes的潜在解决方案.这也使用了该build方法.


use*_*164 10

对于belongs_toRails 3.2中的关联,嵌套模型需要以下两个步骤:

(1)attr_accessible为您的子模型添加新内容(用户模型).

accepts_nested_attributes_for :organization
attr_accessible :organization_attributes
Run Code Online (Sandbox Code Playgroud)

(2)添加@user.build_organization到子控制器(用户控制器)以创建列organization.

def new
  @user = User.new
  @user.build_organization
end
Run Code Online (Sandbox Code Playgroud)


Fáb*_*újo 6

对于 Ruby on Rails 5.2.1

class User < ActiveRecord::Base
  belongs_to :organization
  accepts_nested_attributes_for :organization
end

class Organization < ActiveRecord::Base
  has_many :users
end
Run Code Online (Sandbox Code Playgroud)

刚到你的控制器,假设是“users_controller.rb”:

Class UsersController < ApplicationController

    def new
        @user = User.new
        @user.build_organization
    end
end
Run Code Online (Sandbox Code Playgroud)

和尼克一样的观点:

= form_for @user do |f|
  f.label :name, "Name"
  f.input :name

  = f.fields_for :organization do |o|
    o.label :city, "City"
    o.input :city

  f.submit "Submit"
Run Code Online (Sandbox Code Playgroud)

最后我们看到@user3551164 已经解决了,但是现在(Ruby on Rails 5.2.1)我们不需要 attr_accessible :organization_attributes

  • 我还需要修改我的强参数来完成这项工作。在上面的例子中,我想我需要在我的强参数中添加类似 `organization_attributes: [:city]` 的东西。 (2认同)