ruby-on-rails - ActiveRecord:where 语句中关联模型的引用属性

标签 ruby-on-rails activerecord

我有两个具有 has_many/has_many 关系的模型。我有一个变量 exp_ids,它是一个整数数组,表示一些 ExperienceLevel 记录的 id。我需要编写一个查询,该查询将选择具有这些 id 之一的 ExperienceLevel 的所有 JobDescription

查询必须在名为 job_descriptions 的现有 ActiveRelation 对象上运行,该对象正在通过我的 Controller 中的一些流程控件传递,以根据我的参数过滤结果。

我尝试了下面的这些查询和其他一些变体,但收效甚微。据我所知,ActiveRecord 认为 experience_levels 是一个属性,这导致它失败。

  • job_descriptions.where(experience_levels: exp_ids)
  • job_descriptions.joins(:experience_levels).where(experience_levels.id: exp_ids)
  • job_descriptions.joins(:experience_levels).where(experience_levels: exp_ids)
  • job_descriptions.joins(:experience_levels).where("experience_levels.id IN exp_ids")
  • job_descriptions.includes(:experience_levels).where("experience_levels.id = ?", exp_ids).references(:experience_levels)

这是我的模型:

class JobDescription < ActiveRecord::Base
    has_many :job_description_experience_levels
    has_many :experience_levels, through: :job_description_experience_levels
end

class JobDescriptionExperienceLevel < ActiveRecord::Base
    belongs_to :job_description
    belongs_to :experience_level
end

class ExperienceLevel < ActiveRecord::Base
    has_many :job_description_experience_levels
    has_many :job_descriptions, through: :job_description_experience_levels
end

我不确定我想做的事情是否可能。我对另一个 job_description 过滤器使用了类似的方法,其中我选择了 company_id,但在本例中,company_id 的属性>职位描述

最佳答案

试试这个:

job_descriptions.joins(:job_description_experience_levels).where(job_description_experience_levels: { experience_level_id: exp_ids })

关于ruby-on-rails - ActiveRecord:where 语句中关联模型的引用属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31193081/

相关文章:

ruby-on-rails - NameError:未初始化的常量 Mail::Parsers::ContentTransferEncodingParser

ruby-on-rails - 你如何使用带有 attr_encrypted 的装置

ruby-on-rails - SystemStackError : stack level too deep - sql. 事件记录?

ruby-on-rails - 如何计算 has_many 关联的所有子记录?

ruby-on-rails - PostgreSQL + Rails citext

javascript - 将 javascript 变量传递给 Rails Controller

ruby-on-rails - 当我通过 rvm 使用 rails3 时,如何在 ubuntu 上安装 mysql2 gem?

ruby-on-rails - 奇怪的异常(exception)与delay_job

ruby-on-rails - 在 rspec 中运行测试组

c# - 如何在 ActiveRecord 中将泛型类作为 ColumnType 传递?