【发布时间】:2016-11-16 10:08:26
【问题描述】:
我有一个 Rails 4.1.7 应用程序,其中有 users 和 themes:
class User < ActiveRecord::Base
has_many :themes
end
class Theme < ActiveRecord::Base
belongs_to :user
end
现在,用户可以创建一些自己的主题(然后这些主题将其user_id 设置为用户的id),或者可以使用任何预定义的主题(将user_id 设置为null)
我想做的是:以某种方式更改has_many 关联,以便当我调用@user.themes 时,这会给我带来预定义的主题以及用户的主题。
我尝试过的:
1) 定义实例方法而不是has_many 关联:
class User < ActiveRecord::Base
def themes
Theme.where user_id: [id, nil]
end
end
但由于我想与用户 (includes(:themes)) 一起预先加载主题,所以这不会真正做到。
2) 使用一些作用域 (has_many :themes, -> { where user_id: nil }),但它会提供类似 ... WHERE user_id = 123 AND user_id IS NULL 的 mySql 查询,它返回空。我想用 Rails5 我可以用has_many :themes, -> { or.where user_id: nil } 之类的东西来做到这一点,但现在不能选择更改 Rails 版本。
【问题讨论】:
-
我认为重写关联是一个坏主意,因为没有指定任何用户的
Theme实际上属于每个用户(许多用户),它不是has_one - has_many关系。我建议使用其他方法来实现您的目标。 -
是的,这就是我现在使用的。只是,有时急切加载它会更好......
标签: ruby-on-rails ruby-on-rails-4 overriding has-many eager-loading