I have a Rails 4.1.7 application, where we have users and themes:
class User < ActiveRecord::Base
has_many :themes
end
class Theme < ActiveRecord::Base
belongs_to :user
end
Now, the user can create some own themes (then these themes will have their user_id set to the user's id), or can use any of the predefined themes (having user_id set to null)
What I would like to do is the following: to somehow change the has_many association so that when I call @user.themes, this bring me the predifined themes along with those of the user.
What I have tried:
1) to define an instance method instead of the has_many association:
class User < ActiveRecord::Base
def themes
Theme.where user_id: [id, nil]
end
end
but since I would like to eager-load the themes with the user(s) (includes(:themes)), that won't really do.
2) to use some scope (has_many :themes, -> { where user_id: nil }), but it gives mySql queries like ... WHERE user_id = 123 AND user_id IS NULL, which returns empty. I guess with Rails5 I could do it with something like has_many :themes, -> { or.where user_id: nil }, but changing the Rails version is not an option for now.