【问题标题】:Filtering records by ownership按所有权过滤记录
【发布时间】:2015-09-28 17:38:40
【问题描述】:

抱歉标题,找不到更好的标题来描述我正在尝试做的事情。

previous question 中,一些用户建议我可以简化模型。我没有再获得 cmets,但我认为我这样做是“正确的方式”,因为我需要在连接表中存储其他属性。

反正我的模型是这样设置的。

class Student < ActiveRecord::Base
    has_many :student_notes
    has_many :notes, :through => :student_notes

    has_many :relationships
    has_many :users, :through => :relationships
end

class Note < ActiveRecord::Base
    has_many :student_notes
    has_many :students, :through => :student_notes
end

class StudentNote < ActiveRecord::Base
    belongs_to :student
    belongs_to :note
end

class User < ActiveRecord::Base
    has_many :relationships
    has_many :students, :through => :relationships
    has_many :notes, :through => :students
end

class Relationship < ActiveRecord::Base
  belongs_to :student
  belongs_to :user
end

现在,在我的笔记显示视图中,我有这个:

    ...
    <% @note.students.each do |student| %>
      <tr>
        <td><%= link_to student.full_name, student %></td>
      </tr>
    <% end %>
    ...

这可行,但我只想显示属于 current_user 的学生。 关于如何实现它的任何提示?我想模型中的辅助方法是可行的方法,但我完全迷失了。

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4


    【解决方案1】:

    Student:

    scope :belonging_to, -> (u) { joins(:users).where users: { id: u.id } }
    

    然后:

    @note.students.belonging_to(current_user)...
    

    【讨论】:

      猜你喜欢
      • 2023-03-10
      • 2015-11-30
      • 2021-12-20
      • 2016-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-13
      • 2020-08-17
      相关资源
      最近更新 更多