여기 당신이 원하는 것을 달성 할 수있는 방법입니다 사용해야합니다. 나는 이것을 콘솔에서 테스트 했으므로 작동 할 것입니다. 나는 사람/사람 복수형을 엉망으로 만들었지 만, 당신은 요지를 얻어야한다. 테스트 목적으로 모델에 더미 속성을 부여했습니다.
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 연결은 어떻게 생겼습니까? –
'current_user.projects.find'를 할 수 있다면'current_user.projects.build'도 할 수 없습니까? 찾아 볼 프로젝트가 없다면 그렇게하십시오. – gregates
@ 집합 : 도와 줘서 고마워. 나는 당신이 의미하는 바를 잘 모르겠다. 프로젝트가 없다면 제 '송장'컨트롤러에서 새로운'프로젝트 '를 만들어야한다는 뜻입니까? – Tintin81