Yshmarov
Yshmarov

Reputation: 3729

ruby on rails filtering inside an association

I have scaffold student name:string is_active:boolean and scaffold attendance student_id:integer event_id:integer

Student has_many :attendances

Attendance belongs_to :student

Attendances/_form.html.haml:

= simple_form_for(@attendance) do |f|
  = f.error_notification

  .form-inputs
    = f.association :student
    = f.association :event

  .form-actions
    = f.button :submit

How to edit the association dropdown to see there only students that have is_active : true?

Upvotes: 0

Views: 47

Answers (1)

atw
atw

Reputation: 5840

You will want to separate your logic from your views. So, in the controller method that uses the form above you can define what you want to see in your drop down menu:

def controller_method
  @active_students = Student.where(is_active: true)
end

and in your association in your form you can specify the drop down menu collection to be equal to @active_students:

f.association :student, collection: @active_students

Alternatively, in one line:

f.association :student, collection: Student.where(is_active: true)

Upvotes: 1

Related Questions