首先,我使用一小时前更新的3-1-stable分支的Rails 3.1 。
我正在开发一个应用程序,其中有 3 个基本模型User、Company和Job,这是模型的相关部分:
class User < ActiveRecord::Base
has_many :companies_users, class_name: "CompaniesUsers"
has_many :companies, :through => :companies_users, :source => :company
end
class Company < ActiveRecord::Base
has_many :companies_users, class_name: "CompaniesUsers"
has_many :employees, :through => :companies_users, :source => :user
has_many :jobs, :dependent => :destroy
end
class Job < ActiveRecord::Base
belongs_to :company, :counter_cache => true
end
class CompaniesUsers < ActiveRecord::Base
belongs_to :company
belongs_to :user
end
代码工作得很好,但我一直想知道是否有可能:
我想将工作与雇主联系起来,所以想一想这种情况:用户John是Example的员工,他发布了 Rails Developer 工作,所以我想访问@job.employer,它应该让我回到用户John, 换句话说:
@user = User.find_by_name('john')
@job = Job.find(1)
@job.employer == @user #=> true
所以我想到了两种可能的解决方案
第一个解决方案
class Job
has_one :employer, :through => :employers
end
class User
has_many :jobs, :through => :employers
end
class Employer
belongs_to :job
belongs_to :user
end
第二种解决方案
class Job
has_one :employer, :class_name => "User"
end
class User
belongs_to :job
end
我应该走哪条路线?我的代码对吗?
我还有一个问题,如何摆脱传递给 has_many 的 class_name => "CompaniesUsers" 选项,该类应该是 Singular 还是 Plural ?我应该将其重命名为Employees之类的东西吗?