I don\'t have any ideas. Could you give me any clues (like reference sites). Any help will be appreciated.
Model1: GROUP
It might be quite important to mention that using includes has possibly unwanted side-effects.
if the filtered association is subsequently scoped, all of the original filtering disappears
As it turns out, by scoping on the filtered association we’ve lost any filtering-as-side-effect that we attained from includes. And it’s not because of how we searched, either.
Make sure to read the complete article and alternatively there's a gem for that.
Rails 5+ allows you to do the following:
Group.left_outer_joins(:user_group_cmb)
http://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-left_joins
I believe an includes
will use a LEFT OUTER JOIN
query if you do a condition on the table that the includes
association uses:
Group.includes(:user_group_cmb).where(user_group_cmbs: { user_id: 1 })
Use has_and_belongs_to_many if you just need to link users to groups. Use has_many :through if you need to store additional membership information.
Example:
class User < ActiveRecord::Base
has_and_belongs_to_many :groups
end
class Group < ActiveRecord::Base
has_and_belongs_to_many :users
end
Use a custom joins statement:
Group.joins("left outer join user_group_cmbs as cmb on groups.id = cmb.group_id")
.where("cmb.user_id = ?", 1)
Couldn't comment to an earlier answer because well I don't have 50 reputation. But here's how it worked for me when I ran into below error
includes-referenced relation raises a StatementInvalid exception, complaining it misses a FROM-clause entry. I need to add an explicit call to join, which defaults to being inner.
I had to use .references and mention the table name or for it get added to the FROM-clause