Ruby on Rail - Format for fetching and displaying Dymanic drop down
I have 3 tables: Student
, Subject
and Score
.
(student_id + subject_id)
is added to Score
table. I.e., capturing that sudent '1' has added 'Mathematics' marks with the actual score (say 0-100 range)
开发者_高级运维student id : subjectid Score 1 Mathematics 95
The Add
page of Score
has a "subject" drop down. which is displayed from "subject" table.
When the student wants to add the 2nd subject marks, in the add page, he should not be displayed the previoys added subject in the drop down.
Can anyone tell me how to do this?
Yes, you can do it in the following way (Rails 3.0):
class Subject
scope :not_enrolled_in, lambda{ |user| where("NOT EXISTS(SELECT id FROM scores WHERE user_id = ? AND subject_id = subjects.id)", user.id) }
end
Or this way in Rails 2.x:
class Subject
named_scope :not_enrolled_in, lambda{ |user| { :conditions => ["NOT EXISTS(SELECT id FROM scores WHERE user_id = ? AND subject_id = subjects.id)", user.id] } }
end
You can then get a list of subjects the current user has not enrolled in this way:
Subject.not_enrolled_in(current_user).all
You can then use this list in your select HTML code.
精彩评论