我试图根据子表中列的值选择一个数据库条目。
具体来说,我有一个表格,其中包含公司职员的姓名和联系方式,模型:Officer。一名高级has_many :roles (首席执行官、首席财务官、总裁等);这允许一名官员兼任总裁兼首席执行官、首席运营官和首席技术官以及其他类似的共同组合。
的问题:,我很难根据公司的特定角色来挑选这位官员。(假设我想知道公司首席执行官的名字。)
因此,我设置了以下内容:
class Company < ActiveRecord::Base
has_many :officers
has_many :roles, through: :officers
accepts_nested_attributes_for :officers
end和
class Officer < ActiveRecord::Base
has_many :roles
belongs_to :company
accepts_nested_attributes_for :roles
end和
class Role < ActiveRecord::Base
belongs_to :officer
end所以我试过company.officer.where(roles.role_string: "Chairman of the Board") ...nope
我试过company.roles.where(role_string: "Chairman of the Board").officer ...also不
如有任何指导,将不胜感激!在此之前,非常感谢您。
发布于 2015-01-27 00:40:48
最后,我用以下方法解决了这个问题:(似乎最有效)
@officer_id=company.roles.where(role_string: "President").first.officer_id
@officer=company.officers.find(@officer_id)first.officer_id的原因是,即使一个高级职员有许多角色,也只能允许一个高级人员/公司拥有一个特定的角色。也许有一种更优雅的方法可以做到这一点,但是上面的方法现在起作用了。
发布于 2015-01-25 11:17:23
尝尝这个
1.
@roles = Role.includes(:officers).where(role_string: "Chairman of the Board")转一圈找到那个警官。
@roles.each do |role|
puts role.officer
end2.
Company.includes(:roles).where('roles.role_string =?', "Chairman of the Board")发布于 2015-01-25 11:06:41
这将导致n:m关系:
class Company < ActiveRecord::Base
has_many :officers
has_many :roles, through: :officers
end
class Role < ActiveRecord::Base
has_many :officers
has_many :companies, through: :officers
end
class Officer < ActiveRecord::Base
belongs_to :company
belongs_to :role
endhttps://stackoverflow.com/questions/28135432
复制相似问题