我将从粘贴相关代码开始,稍后我将解释我要做什么
class User < ActiveRecord::Base
has_many :compus, :dependent => :destroy
has_many :companies, :through => :compus
end
class Company < ActiveRecord::Base
has_many :compus, :dependent => :destroy
has_many :employees, :through => :compus, :source => :user
has_one :owner, :through => :compus, :source => :user, :conditions => { :owner => true }
end
class Compu < ActiveRecord::Base
belongs_to :company
belongs_to :user
end
compus 表具有以下列(从迁移中复制)
create_table :compus do |t|
t.references :company
t.references :user
t.string :job_title
t.boolean :owner, null: false, default: false
t.timestamps
end
如您所见,我有一个用户可以创建 n 家公司并在 n 家公司工作,在公司工作并不意味着他是所有者。
我想得到的是:
user.companies #=> 用户创建或工作的公司(我担心稍后会过滤结果)
company.employees #=> 在这家公司有工作的所有用户(通过 compus)
company.owner #=> 最初创建公司的一个用户(或者如果稍后转移另一个用户)
所以我在编写上面的代码之前添加了以下规范。
it "has one owner" do
company = Factory(:company)
user = Factory(:user)
company.should respond_to(:owner)
user.companies << company
company.owner.should === user
end
但我收到以下错误:
ActiveRecord::HasOneThroughCantAssociateThroughCollection:
Cannot have a has_one :through association 'Company#owner' where the :through association 'Company#compus' is a collection. Specify a has_one or belongs_to association in the :through option instead.
那么如何在不向公司表中添加更多列的情况下解决此问题,如果我在公司表中添加owner_id会更容易,但这会导致数据库中的重复,通常如果用户创建了公司,则意味着他在它
我遇到的另一个问题是,如何通过关联轻松访问 compus 表上的 :job_title ?