ruby-on-rails – rails has_one通过集合
发布时间:2020-12-17 02:41:46 所属栏目:百科 来源:网络整理
导读:我将首先粘贴相关代码,然后我将在稍后解释我想要做什么 class User ActiveRecord::Base has_many :compus,:dependent = :destroy has_many :companies,:through = :compusendclass Company ActiveRecord::Base has_many :compus,:dependent = :destroy has_m
我将首先粘贴相关代码,然后我将在稍后解释我想要做什么
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,: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? 解决方法
您可以创建一个函数来返回所有者
def owner compus.where(:owner => true).first end 在数据库设计方面,如果要将公司限制为一个所有者,最好将owner_id列放在公司表中.否则你必须始终强制他们只是一个所有者,而且会更复杂. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |