0

생성자를 추가하지 않습니다 난간은 다음과 같은 모델 설정을위한 User.build_company 방법을 생성하지 않는 이유를 알아낼 수 없습니다 :has_one :를 통해 : 나는 상당히 레일에 새로운 액티브 해요

class User < ActiveRecord::Base 
    has_one :found_company 
    has_one :company, through: :found_company 
end 

class FoundCompany < ActiveRecord::Base 

    belongs_to :user 
    belongs_to :company 
end 

class Company < ActiveRecord::Base 
    has_many :found_companies 
    has_many :users, through: :found_companies 
end 

이를

class User < ActiveRecord::Base 
    has_many :found_companies 
    has_many :companies, through: :found_companies 
end 
:

irb(main):035:0> user = User.all.first 
    ?[1m?[36mUser Load (1.0ms)?[0m ?[1mSELECT "users".* FROM "users" ?[0m 
    => #<User id: 1, email: "[email protected]" [...] uid: nil> 
    irb(main):036:0> user.build_company 
NoMethodError: undefined method `build_company' for #<User:0x5bd50e0> 

내가 변경하는 경우 has_one: through 예상 작동으로 모든 has_many: through에 : 나는 빌드 메서드를 호출 할 때 발생하는 것입니다

호출 user.companies.build 잘 작동합니다 :

irb(main):041:0> f.companies.build 
=> #<Company id: nil, name: nil, created_at: 
[...] 
irb(main):041:0> 

왜 빌더 방법을 생성하는 것 같지 has_one: through는 무엇입니까?

답변

0

지금까지 내가 알고있는 한 user.companies.build은 올바른 구문입니다. 나는 .build_company을 인스턴스화와 관련된 항목으로 인식하지 못합니다. 레일이 방법을 제공하지 않는 이유를 모르겠어요

+0

AFAIK, 협회 has_one과 belongs_to 실제로 build_association 아니라 객체입니다. other.build –

0

, 다음을 수행하여 당신이 그러나 원하는 것을 얻을 수 있습니다

user.build_found_company.build_company 
+0

와우, 그건 효과가 있지만 너무 어색해 보입니다. 왜 내가 회사에 직접 액세스 할 수있는 has_many와 대조적으로 join 테이블을 명시 적으로 처리해야합니까? –