activerecord - how to perform a search query of a foreign key field's attribute in rails? -
i have 2 models exam
, student
.
exam.rb
class exam < applicationrecord belongs_to :year belongs_to :student, class_name: "student" def self.search(search) if search self.where('student. ?', "%#{search}%") else self.all end end end
student.rb
class student < applicationrecord belongs_to :year has_many :exams end
the student
field in exam.rb
refers student object . model student
has attribute name
, want perform search based on attribute , find out list of exams taken student . possible make such query ? if , correct way implement ?
thanks
you can implement using joins
, where
:
exams_list = exams.joins(:student).where('students.name ?', "%#{search}%"))
hope helps.
Comments
Post a Comment