我对 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
这是我尝试调用 build 方法时发生的情况:
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
生成构建器方法?