我想在我的视图中通过school_user_id过滤完成的选项。这是从这个问题开始的:RoR: Mark an object complete, save completed_on in other model
因此,学生可以完成一件作业。但在视图中,它提供了4个完整的选项,因为4个学校用户与该作业相关联。我正在尝试过滤,以便只有当前的school_user完整选项可用。
User和School_user有一对一的关系。
在我看来(这不起作用,什么也不渲染,如果删除where语句会呈现4个完整选项)
家庭作业/ show.html.erb
<% @homework.homework_students.where(school_user_id: current_user.id).each do |homework_student| %>
<%= link_to "complete", complete_homework_path(:homework_id => @homework, :home_work_students_id => homework_student), method: :patch %>
<% end %>
型号:
school_user.rb
has_many :homework_students, :class_name => 'HomeworkStudent'
has_many :homeworks, :class_name => 'Homework'
homework_student.rb
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
homework.rb
has_many :homework_students, :class_name => 'HomeworkStudent', dependent: :destroy
belongs_to :school_user, :class_name => 'SchoolUser', :foreign_key => :school_user_id
如果我过滤其他地方,我会做这样的事情:
<% if homework.school_user.user_id == current_user.id %>
从rails控制台:
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>
正如您所见,school_user_id就在那里。这只是过滤掉其他用户完成的其他用户的情况。但我不知道如何用for_each做到这一点。
感谢任何帮助。谢谢。如果需要,可以提供更多代码/信息。
更新:
<% @homework.homework_students.joins(:school_user).where(school_user: { user_id: current_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
答案 0 :(得分:1)
应该是
@homework.homework_students.joins(:school_user).where(school_users: { user_id: current_user.id }).each