gpt4 book ai didi

ruby-on-rails - Rails 4 中的多范围 has_many 关系

转载 作者:行者123 更新时间:2023-12-04 03:40:30 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Losing an Attribute When Saving Through an Association w/ Scope (Rails 4.0.0)

(1 个回答)


8年前关闭。




我想对模型 User 和 Event 之间的这种关系进行建模。


因此,我从以下类(class)开始:

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”的关联)
这里的问题是,where 谓词是在表 'users' 上评估的。
我不知道如何“正确”解决这个问题,而不为每个状态引入新的连接表/模型。特别是因为每个用户对于每个事件都只能处于一种状态,我认为具有一个出勤模型的解决方案是有意义的。
你有什么想法,如何做到这一点?

最佳答案

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

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

更好的是,将此范围添加到出勤模型并将其合并到:
class Attendance < ActiveRecord::Base
def self.unexcused
where state: 'unexcused'
end
end

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

关于ruby-on-rails - Rails 4 中的多范围 has_many 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17391832/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com