下面就來完成你想要的方式。我在我的控制檯中測試了它,所以它應該可以工作。我搞砸了人/人的多元化,但你應該明白。爲了測試目的,我給模型賦予了虛擬屬性。
class User < ActiveRecord::Base
attr_accessible :name
has_many :persons
class Person < ActiveRecord::Base
attr_accessible :person_name, :user_id
belongs_to :user
has_many :projects
has_many :people_invoices
has_many :invoices, through: :people_invoices
class Project < ActiveRecord::Base
attr_accessible :person_id, :project_name, :user_i
belongs_to :person
has_many :invoices
class PeopleInvoice < ActiveRecord::Base
attr_accessible :invoice_id, :person_id
belongs_to :person
belongs_to :invoice
class Invoice < ActiveRecord::Base
attr_accessible :invoice_amount, :person_id
belongs_to :project
has_many :people_invoice
has_many :persons, through: :people_invoices
我給一些虛擬屬性,每個模型,你可以在上面的attr_accessible領域看到的。
在我的控制檯,我想:
@user = User.new(name: "User")
@person = @user.persons.create(person_name: "Employee")
@project = @person.projects.create(project_name: "foo")
@invoice = @project.invoices.create(invoice_amount: 25)
@person_invoice = @person.people_invoices.create(invoice_id:1)
與您的協會這樣,那麼你可以撥打:
@user = User.find(4)
<User id: 4, name: "User", created_at: "2012-10-19 20:18:28", updated_at: "2012-10-19 20:18:28">
@user.persons
=> [#<Person id: 5, user_id: 4, person_name: "Employee", created_at: "2012-10-19 20:19:00", updated_at: "2012-10-19 20:19:00">]
@person.invoices
[#<Invoice id: 1, project_id: 2, invoice_amount: 25, created_at: "2012-10-19 19:33:10", updated_at: "2012-10-19 19:33:10">]
因爲關聯,你應該能夠找到相應的發票項目和人員,並追溯到特定用戶。由於關係是has_many,你會得到數組返回給你(注意最後兩個控制檯輸出中的括號)。然後您必須在塊中循環查看或訪問特定值。
希望這會有所幫助!
你的ActiveRecord關於'people'的外觀是什麼樣子的? –
如果你可以做'current_user.projects.find'你不能也''current_user.projects.build'嗎?只要做到這一點,如果沒有項目要查找。 – gregates
@gregates:感謝您的幫助。我不確定我明白你的意思。你的意思是如果沒有項目存在,我應該在我的'invoice'控制器中建立一個新的'project'? – Tintin81