使用外键关联搜索
Search with foreign key association
我有一个如下所示的关联:
belongs_to :question,
-> { where lang: I18n.locale },
class_name: "Translation",
foreign_key: 'question_tid',
primary_key: 'id'
has_many :questions,
class_name: "Translation",
foreign_key: 'id',
primary_key: 'question_tid'
架构如下:
#
# id :integer not null, primary key
# question_tid :integer
# category_id :integer
# default_answer_tid :integer
# created_at :datetime
# updated_at :datetime
#
我正在尝试执行这样的搜索查询:
def self.find_by_search(search)
return includes(:question).
where("question like ?", "%#{search}%").
sort_by { |q| ActiveSupport::Inflector.transliterate(q.question.text) }
end
不过where好像不认识问题关联。我怎样才能让它明白我想要加入翻译 table 的 'question' 字段?
谢谢
写下来:
def self.find_by_search(search)
return includes(:question).
where("question like ?", "%#{search}%").
references(:question).
sort_by { |q| ActiveSupport::Inflector.transliterate(q.question.text) }
end
文档 includes
清楚地说:
conditions: If you want to add conditions to your included models you’ll have to explicitly reference them
我有一个如下所示的关联:
belongs_to :question,
-> { where lang: I18n.locale },
class_name: "Translation",
foreign_key: 'question_tid',
primary_key: 'id'
has_many :questions,
class_name: "Translation",
foreign_key: 'id',
primary_key: 'question_tid'
架构如下:
#
# id :integer not null, primary key
# question_tid :integer
# category_id :integer
# default_answer_tid :integer
# created_at :datetime
# updated_at :datetime
#
我正在尝试执行这样的搜索查询:
def self.find_by_search(search)
return includes(:question).
where("question like ?", "%#{search}%").
sort_by { |q| ActiveSupport::Inflector.transliterate(q.question.text) }
end
不过where好像不认识问题关联。我怎样才能让它明白我想要加入翻译 table 的 'question' 字段?
谢谢
写下来:
def self.find_by_search(search)
return includes(:question).
where("question like ?", "%#{search}%").
references(:question).
sort_by { |q| ActiveSupport::Inflector.transliterate(q.question.text) }
end
文档 includes
清楚地说:
conditions: If you want to add conditions to your included models you’ll have to explicitly reference them