Co2 Co2 - 10 months ago 41
Ruby Question

RoR: Filtering user options in for_each loop

I am trying to filter options for complete by school_user_id in my view. This follows on from this question: RoR: Mark an object complete, save completed_on in other model

So a student is able to mark a piece of homework complete. But in the view it is rendering 4 complete options because 4 school_users are associated with that piece of homework. I am trying to filter so that only the current school_user's complete option is available.

User and School_user have a one to one relationship.

In my view (this does not work and renders nothing, if where statement removed renders 4 complete options)


<% @homework.homework_students.where(school_user_id: do |homework_student| %>
<%= link_to "complete", complete_homework_path(:homework_id => @homework, :home_work_students_id => homework_student), method: :patch %>
<% end %>



has_many :homework_students, :class_name => 'HomeworkStudent'
has_many :homeworks, :class_name => 'Homework'


has_many :homework_ratings, :class_name => 'HomeworkRating'
belongs_to :homework, :class_name => 'Homework', :foreign_key => :homework_id, dependent: :destroy
belongs_to :school_user, :class_name => 'SchoolUser', :foreign_key => :school_user_id


has_many :homework_students, :class_name => 'HomeworkStudent', dependent: :destroy
belongs_to :school_user, :class_name => 'SchoolUser', :foreign_key => :school_user_id

If I was filtering else where I would do something like this:

<% if homework.school_user.user_id == %>

From the rails console:

irb(main):002:0> search = HomeworkStudent.find(142)
HomeworkStudent Load (0.5ms) SELECT `homework_students`.* FROM `homework_students` WHERE `homework_students`.`id` = 142 LIMIT 1
=> #<HomeworkStudent id: 142, school_user_id: 10001, homework_id: 78, completed_on: "2016-11-23 18:05:34", created_at: "2016-11-22 00:27:24", updated_at: "2016-11-23 18:05:34", completed: nil>

As you can see school_user_id is there. It's just a case of filtering out the other completes which are for other users with that homework. But I don't know how to do this with for_each.

Appreciate any help. Thanks.Happy to provide more code/info if needed.


<% @homework.homework_students.joins(:school_user).where(school‌​_user: { user_id: }).each do |homework_student| %>


Mysql2::Error: Unknown column 'school‌​_user.user_id' in 'where clause': SELECT `homework_students`.* FROM `homework_students` INNER JOIN `school_users` ON `school_users`.`id` = `homework_students`.`school_user_id` WHERE `homework_students`.`homework_id` = 78 AND `school‌​_user`.`user_id` = 1

Answer Source

Should be

@homework.homework_students.joins(:school_user).where(school‌​_users: { user_id: }).each