簡體   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