2016-02-23 104 views
0

我有scaffold student name:string is_active:booleanscaffold attendance student_id:integer event_id:integerRuby on Rails的关联内部过滤

Student has_many :attendances 

Attendance belongs_to :student 

出勤/ _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 

如何编辑协会下拉菜单看到有只让学生is_active : true

回答

1

你会想要从你的意见中分离出你的逻辑。因此,在使用你上面的表格可以定义要在您的下降看到下拉菜单什么的控制器方法:

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

,并在你的表格关联中,你可以指定下拉菜单collection相等到@active_students

f.association :student, collection: @active_students 

或者,在一个行:

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

我试图第二个。它有效,但是当我去考勤/编辑时,如果学生字段不再有效,它显示为空白。这能解决吗? –

+0

那么,如果您的数据库中只有一名学生,而他/她没有激活,那么下拉菜单中将不会显示任何内容。你想要发生什么? –

+0

如果例如我想编辑'= f.association:event',并且学生不再活跃,它将显示一个空白'= f.association:student' ... –