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

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

概述这个问题与以下内容完全相同:            >             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...endclass Attendance < ActiveRecord::Base# with columns user_ID and event_ID...endclass 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'  endendclass Event < ActiveRecord::Base  has_many :unexcused_absent_users,-> { merge(Attendance.unexcused) },:source => :user      end
总结

以上是内存溢出为你收集整理的ruby-on-rails – 在Rails 4中使用多个作用域的has_many关系全部内容,希望文章能够帮你解决ruby-on-rails – 在Rails 4中使用多个作用域的has_many关系所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1290564.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-09
下一篇 2022-06-09

发表评论

登录后才能评论

评论列表(0条)

保存