繁体   English   中英

Ruby on Rails:接受父记录而不是子记录的嵌套属性?

[英]Ruby on Rails: Accept nested attributes for parent rather than child records?

在我的Rails应用程序中, Users可以有很多People ,这些人又可以(但不必)属于Organisations

简而言之,这是:

Users --< People >-- Organisations

现在,能够以某种人的视角在内部创建新组织将是一件很高兴的事情。 它尝试这样做:

class Person < ActiveRecord::Base

  attr_accessible :name, :organisation_attributes

  belongs_to :user
  belongs_to :organisation

  accepts_nested_attributes_for :organisation

end

但这是行不通的,因为组织不是Person的孩子。

还有另一种方法可以实现这一目标吗?

谢谢你的帮助。

我可以看到Person实际上是Organisation的子代,并且也可以为父模型创建嵌套形式。 并且您已经在使用accepts_nested_attributes_for

我假设您想显示一个已经保存的personOrganisation形式。 然后

在您的PeopleController#show方法中建立组织

@person.build_organisation

并在people/show.html.erb

form_for(@person) do |f|
    f.fields_for(:organisation) do |fo|
        # show the fields of organisation here.
    end
end

它应该工作。

更新:

我尝试了类似的方法,但效果很好:)我弄了包括摘要在内的要点。 请点击链接https://gist.github.com/3841507,以查看它是否有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM