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

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -