我的关联看起来像:
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
然而,在哪里似乎没有认识到问题关联。如何理解我想要在翻译表上加入的“问题”字段?
由于
答案 0 :(得分:3)
写下来:
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
的文件清楚地说:
条件:如果您想为所包含的模型添加条件,则必须明确引用它们