Reputation: 57
I have three models:
class User < ActiveRecord::Base
has_many :rosterplayers
has_many :rosters, -> { uniq } , :through => :rosterplayers
end
class Roster < ActiveRecord::Base
has_many :rosterplayers
has_many :users, -> { uniq }, through: :rosterplayers
end
class Rosterplayer < ActiveRecord::Base
belongs_to :roster
belongs_to :user
validates :user_id, :uniqueness => { :scope => :roster_id }
end
The Rosterplayer table has three columns: user_id
, roster_id,
and pending
(boolean)
Question: Given a roster, how would I retrieve all users that are currently pending?
Attempt: My first attempt was to loop through all the users in the roster:
@team.rosters[0].users.each do |u|
Rosterplayer.find_by(roster_id: rosters[0].id, user_id: u.id, pending: true)
end
But I feel like there is a better way of doing it.
Upvotes: 3
Views: 628
Reputation: 54882
You can achivete this by doing the following:
User.includes(:rosterplayers).where(rosterplayers: { pending: true })
This will return all User records having at least 1 rosterplayer
having pending
set to true
.
Limit the query to a specific roster
instance:
User.includes(:rosterplayers).where(rosterplayers: { pending: true, roster_id: your_roster_id })
# your_roster_id can actually be an array of IDs
Additional note: Be carefull with .joins and .includes:
# consider these models
Post
belongs_to :user
#^^
User
has_many :posts
#^
# the `includes/joins` methods use the name defined in the model :
User.includes(:posts).where(posts: { title: 'Bobby Table' })
#^ ^
# but the `where` uses the pluralized version (table's name) :
Post.includes(:user).where(users: { name: 'Bobby' })
#^^^ ^
Similar questions:
Upvotes: 5