2012-10-19 2 views
0

user에 많은 people을 가질 수있는 응용 프로그램이 있습니다. 많은 projects에 많은 invoices을 포함 할 수 있습니다.더 멀리있는 연관에서 외래 키를 설정하는 방법은 무엇입니까?

def create 
    project = current_user.projects.find(params[:invoice][:project_id])  
    @invoice = project.invoices.build(params[:invoice]) 
    if @invoice.save 
    flash[:success] = "Invoice created." 
    redirect_to invoices_path 
    else 
    render :action => "new" 
    end 
end 

문제가 더 project_id이없는 때마다 오류가 발생한다는 것입니다 : 내 invoice 컨트롤러

나는이 작업을해야합니다.

나는 그것을 이해하고 대신이 같은 시도 ...

@invoice = current_user.people.projects.invoices.build(params[:invoice]) 

을 ...하지만 난 다음 undefined method projects 오류가 발생합니다.

새로운 invoice이 자동으로 올바른 user과 연결되며 누구도이를 무단으로 변경할 수 있는지 확인하고 싶습니다.

그렇게 할 방법이 있습니까?

+1

'사람'과 관련된 ActiveRecord 연결은 어떻게 생겼습니까? –

+0

'current_user.projects.find'를 할 수 있다면'current_user.projects.build'도 할 수 없습니까? 찾아 볼 프로젝트가 없다면 그렇게하십시오. – gregates

+0

@ 집합 : 도와 줘서 고마워. 나는 당신이 의미하는 바를 잘 모르겠다. 프로젝트가 없다면 제 '송장'컨트롤러에서 새로운'프로젝트 '를 만들어야한다는 뜻입니까? – Tintin81

답변

-1

당신은 through

class User < ActiveRecord::Base 
    has_many :projects 
    has_many :invoices, through: projects 
end 

class Invoice < ActiveRecord::Base 
    has_many :projects 
    has_one :user, through: projects 
end 

class Project < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :invoice 
end 
+0

나는 사실이다! 그러나'through '는 내가 아는 한 3 개의 협회 만 연결할 수있다 ...? 나는 네 가지가있다. – Tintin81

+0

좋아, 나는 네가 너의 관계를 조금 모호하게 만든 것 같아. 인보이스에 1 명의 사용자 만있을 수있는 경우 사용자와 인보이스간에 직접적인 관계를 형성해야합니다. – tagCincy

1

여기 당신이 원하는 것을 달성 할 수있는 방법입니다 사용해야합니다. 나는 이것을 콘솔에서 테스트 했으므로 작동 할 것입니다. 나는 사람/사람 복수형을 엉망으로 만들었지 만, 당신은 요지를 얻어야한다. 테스트 목적으로 모델에 더미 속성을 부여했습니다.

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이기 때문에 배열이 반환 될 것입니다 (마지막 두 콘솔 출력에서 ​​대괄호에 주목하십시오). 그런 다음 특정 값을 보거나 액세스하려면 블록을 순환해야합니다.

희망이 도움이됩니다.

+0

안녕하세요, 도움에 많은 감사드립니다! 필자는 왜 새로운 모델 인'PeopleInvoice'가 필요한지 궁금합니다. 그걸 나에게 설명해 주시겠습니까? – Tintin81

+0

예. 나는 일종의 "교량"으로 사용했습니다.PeopleInvoices는 인보이스와 관련된 인보이스가 프로젝트를 통해 전송되는 것은 아니기 때문에 사람과 인보이스에 직접 연결되는 방식이기 때문에 직접 연결하는 데 필요한 키가있는 기본적으로 JOIN 테이블입니다. 아마도 HABTM 관계를 사용하는 것이지만, 이것보다 유연합니다 (여기 2.8 섹션 참조 : http://guides.rubyonrails.org/association_basics.html#choosing-between-has_many-through-and-has_and_belongs_to_many). – jflores

관련 문제