我对rails和ActiveRecord相当新,我无法弄清楚为什么rails不会为以下模型设置生成User.build_company
方法:
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
当我尝试调用构建方法时会发生这种情况:
irb(main):035:0> user = User.all.first
?[1m?[36mUser Load (1.0ms)?[0m ?[1mSELECT "users".* FROM "users" ?[0m
=> #<User id: 1, email: "user@example.com" [...] uid: nil>
irb(main):036:0> user.build_company
NoMethodError: undefined method `build_company' for #<User:0x5bd50e0>
如果我将has_one: through
更改为has_many: through
,一切都按预期工作:
class User < ActiveRecord::Base
has_many :found_companies
has_many :companies, through: :found_companies
end
调用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 :(得分:0)
据我所知user.companies.build
是正确的语法。我不知道.build_company
是实例化相关项的一种方式。
答案 1 :(得分:0)
我不知道为什么Rails不提供这种方法,你可以通过以下方式实现你想要的目标:
user.build_found_company.build_company