gpt4 book ai didi

ruby-on-rails - Rails has_many :through - Is it possible to have a conditions in the through table?

转载 作者:行者123 更新时间:2023-12-03 01:33:53 24 4
gpt4 key购买 nike

有 2 个模型,它们使用 has_many :though 关系链接。

有一个 :conditions 参数,它将在另一个模型表中查找条件,但是有没有办法在连接表中创建条件?

例如,假设我有:

User
Game
GameUser

一个用户可能有很多游戏,就像一个游戏可能有很多用户一样。但我想在联合表中存储额外的信息,例如用户是否喜欢该游戏。

我想在我的用户模型中有一个关系过滤器,如下所示:

has_many :games, :through => 'game_users'   
has_many :liked_games, :through => 'game_users', :conditions_join => { :like => true }

有没有一种很好的方法来实现这个功能?

最佳答案

Jochen 的链接有一个很好的解决方案 - 但 :conditions 已被弃用,并且 :conditions => ['event_users.active = ?',true] 位只是不赞成'看起来很不合规矩。试试这个:

has_many :game_users
has_many :game_likes, -> { where like: true }, class_name: 'GameUser'
has_many :liked_games, :through => :game_likes, class_name: 'Game', :source => :game

关于ruby-on-rails - Rails has_many :through - Is it possible to have a conditions in the through table?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4115554/

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