【问题标题】:Selecting Parent database entry based on child column value根据子列值选择父数据库条目
【发布时间】:2015-01-25 10:34:59
【问题描述】:

我正在尝试根据子表中列的值来选择数据库条目。

具体来说,我有一个包含公司官员姓名和联系信息的表格,型号:Officer。一名官员has_many :roles(CEO、CFO、总裁等);这允许一名官员兼任总裁兼首席执行官、首席运营官和首席技术官以及其他此类常见组合。

问题:我正在努力根据公司的特定角色来选择主管。 (假设我想知道公司 CEO 的名字。)

所以我设置了以下内容:

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") ...不

我试过company.roles.where(role_string: "Chairman of the Board").officer ...也不行

任何指导将不胜感激!非常感谢。

【问题讨论】:

  • @Nithin 非常感谢您的回复。这似乎让我走得更远。我怎么能在一个列中要求一个值呢?我试过Role.includes(:officers).where(role_string: "Chairman of the Board").fname(试图得到警官的名字)但没有用。

标签: ruby-on-rails database ruby-on-rails-4 crud


【解决方案1】:

试试这个

1.

@roles = Role.includes(:officers).where(role_string: "Chairman of the Board")

循环并找到警官。

@roles.each do |role|
 puts role.officer
end

2.

Company.includes(:roles).where('roles.role_string =?', "Chairman of the Board")

【讨论】:

  • 感谢您的回复,我尝试了第一个,但无法弄清楚如何最终引用 :officers 表中的列。说我想参考官员专栏fname,我试过Role.includes(:officers).where(role_string: "Chairman of the Board").fname,但没用。我怎样才能得到这个列值?
【解决方案2】:

这将导致 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
end

【讨论】:

  • 所以这意味着我需要向官员添加一个role_id 列?
  • 确保与您的Officer模型相关的迁移包含t.references :company t.references :role 这将添加所需的外键
【解决方案3】:

最终我用以下方法解决了它:(似乎最有效)

@officer_id=company.roles.where(role_string: "President").first.officer_id
@officer=company.officers.find(@officer_id)

first.officer_id 的原因是只允许一名官员/公司担任给定角色,即使一名官员有多个角色。可能有一种更优雅的方法可以做到这一点,但上述方法目前有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    • 1970-01-01
    • 2013-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多