这是一种实现您想要的方法。我在控制台中对此进行了测试,所以它应该可以工作。我搞砸了人/人的多元化,但你应该明白要点。我为模型提供了虚拟属性以进行测试。
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,因此您将获得返回给您的数组(注意最后两个控制台输出中的括号)。然后,您必须在一个块中循环浏览它们以查看或访问特定值。
希望这可以帮助!