Ruby on rails 3 是否接受\u嵌套的\u属性\u以使用所属的\u?

Ruby on rails 3 是否接受\u嵌套的\u属性\u以使用所属的\u?,ruby-on-rails-3,nested-attributes,belongs-to,Ruby On Rails 3,Nested Attributes,Belongs To,关于这个基本问题,我得到了各种相互矛盾的信息,而答案对于我目前的问题来说非常关键。那么,非常简单,在Rails 3中,允许或不允许将accepts\u嵌套的\u属性\u用于具有归属关系的对象吗 class User < ActiveRecord::Base belongs_to :organization accepts_nested_attributes_for :organization end class Organization < ActiveRecord::Ba

关于这个基本问题,我得到了各种相互矛盾的信息,而答案对于我目前的问题来说非常关键。那么,非常简单,在Rails 3中,允许或不允许将accepts\u嵌套的\u属性\u用于具有归属关系的对象吗

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

class Organization < ActiveRecord::Base
  has_many :users
end

doc epochwolf引用了第一行“嵌套属性允许您通过父项保存关联记录上的属性”(我的重点)

你可能会对它感兴趣。它描述了两种可能的解决方案:1)将accepts_嵌套的_属性移动到关系的另一端(在本例中为组织),或2)在呈现表单之前在用户中构建组织


我还发现了一个要点,它描述了您是否愿意处理一些额外的代码。这也使用了
build
方法。

从Rails 4开始,嵌套属性似乎可以很好地用于归属关联。它可能在早期版本的Rails中被更改了,但我在4.0.4中进行了测试,它肯定能按预期工作。

因为
属于Rails 3.2中的
关联,嵌套模型需要以下两个步骤:

(1) 向子模型(用户模型)添加新的
attr\u accessible

(2) 将
@user.build_organization
添加到您的子控制器(用户控制器)以创建列
组织

def new
  @user = User.new
  @user.build_organization
end

适用于RubyonRails 5.2.1

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

class Organization < ActiveRecord::Base
  has_many :users
end

最后我们看到@user3551164已经解决了,但是现在(Ruby on Rails 5.2.1)我们不需要
attr\u accessible:organization\u attributes

文档没有提到
属于
,所以我对此表示怀疑。为什么不试试,然后再联系我们呢?我能够验证至少在Rails 5.2中,答案是肯定的,它是有效的。帮助我。仍然在Rails 4.1.1中,接受嵌套属性不适用于多态属性。我不得不把它移到协会的另一边。这只是为了与他人分享信息。我同意kid_drew的观点。我刚刚在Rails版本4.2.9中使用了它。我正在这样做,但在使用它时遇到了很多问题。让父对象为其子对象接受嵌套参数似乎不足以让它正确构建,它希望我已经更新了Rails 4的要点:对于那些正在寻找答案的人来说,
接受嵌套属性的方法可以与
所属的属性一起工作,我发现这是最有帮助的。我还需要修改我的强参数以使其工作。在上面的例子中,我想我需要在我的强参数中添加类似于
organization\u attributes:[:city]
def new
  @user = User.new
  @user.build_organization
end
class User < ActiveRecord::Base
  belongs_to :organization
  accepts_nested_attributes_for :organization
end

class Organization < ActiveRecord::Base
  has_many :users
end
Class UsersController < ApplicationController

    def new
        @user = User.new
        @user.build_organization
    end
end
= 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"