加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 在Rails 4中使用多个作用域的has_many关系

发布时间:2020-12-17 03:05:29 所属栏目:百科 来源:网络整理
导读:这个问题与以下内容完全相同:???????????????????????? Losing an Attribute When Saving Through an Association w/ Scope (Rails 4.0.0)????????????????????????????????????1个 我想模拟User和Event模型之间的这种关系. 因此我开始使用以下类: class U
这个问题与以下内容完全相同:????????????>???????????? Losing an Attribute When Saving Through an Association w/ Scope (Rails 4.0.0)????????????????????????????????????1个
我想模拟User和Event模型之间的这种关系.

因此我开始使用以下类:

class User < ActiveRecord::Base
...
end

class Attendance < ActiveRecord::Base
# with columns user_id and event_id
...
end

class Event < ActiveRecord::Base
  has_many :attendances
  has_many :users,:through => :attendances
  ...
end

到目前为止一切正常:我可以分配用户和访问考勤.但现在我想把国家发挥作用,这样我就可以区分,例如在“参加”,“无故缺席”,…用户之间.我的第一次尝试是:

class Event < ActiveRecord::Base
  has_many :attendances
  has_many :users,:through => :attendances
  has_many :unexcused_absent_users,-> { where :state => 'unexcused' },:through => :attendances,:source => :user
  ...
end

(:必须指定source,否则它将搜索名为’unexcused_absent_users’的属于该关联的属性)
这里的问题是,在表’users’上评估where-predicate.

如果没有为每个州引入新的连接表/模型,我无法如何正确地解决这个问题.特别是因为每个用户都可以在每个事件中处于一个状态,我认为使用一个出勤模型的解决方案是有意义的.

你知道吗,如何做到这一点?

解决方法

您可以简单地缩小范围以查看正确的表:

has_many :unexcused_absent_users,-> { where(attendances: {state: 'unexcused'}) },:source => :user

Evem更好,将此范围添加到Attendance模型并将其合并到:

class Attendance < ActiveRecord::Base
  def self.unexcused
    where state: 'unexcused'
  end
end

class Event < ActiveRecord::Base
  has_many :unexcused_absent_users,-> { merge(Attendance.unexcused) },:source => :user      
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读