How does one query for lateral grandparent in Ruby on Rails?
For instance I have the following models setup:
User
class User < ActiveRecord::Base
has_many :registrations
end
Registration
class Registration < ActiveRecord::Base
belongs_to :user
belongs_to :competition
end
Competition
class Competition < ActiveRecord::Base
has_many :registrations
belongs_to :tournament
end
Tournament
class Tournament < ActiveRecord::Base
has_many :competitions
end
So what I want to do is find all Users who have Registrations belonging to a particular Tournament. The only way I know of to do this is by finding all users, looping through each of them and then querying each users individual registrations like so…
<% @users.each do |user| %>
<% if user.registrations..joins(:competition).where("competitions.tournament_id = #{params[:tournament]}").count > 0 %>
print out user information...
<% end %>
<% end %>
This seems like a real half-youknowwhat way of doing things because I’m selecting records that I don’t need, can anybody suggest a better more Railsy way of accomplishing this?
The first step I would take to create a more “Railsy” solution would be to move the query logic out of the view and into the model layer. You could add these two queries to your Tournament model:
Now within a view you can:
You also have a method that returns all the registrations in a tournament, should you ever need it. Hope this helps you see another approach.