jmasterx
jmasterx

Reputation: 54113

Search with foreign key association

I have an association that looks like:

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'

Schema looks like:

#
#  id                 :integer          not null, primary key
#  question_tid       :integer
#  category_id        :integer
#  default_answer_tid :integer
#  created_at         :datetime
#  updated_at         :datetime
#

I am trying to do a search query like this:

def self.find_by_search(search)
        return includes(:question).
               where("question like ?", "%#{search}%").
               sort_by { |q| ActiveSupport::Inflector.transliterate(q.question.text) }
    end

However, the where does not seem to recognize the question association. How can I make it understand that I want the 'question' field which joins on the translation table?

Thanks

Upvotes: 1

Views: 193

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118271

Write it:

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

Documentation of includes clearly said :

conditions: If you want to add conditions to your included models you’ll have to explicitly reference them

Upvotes: 3

Related Questions