Noz
Noz

Reputation: 6346

Rails 3 Finding A Child's Grandparent Through It's Other Parent

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?

Upvotes: 1

Views: 674

Answers (1)

Don Leatham
Don Leatham

Reputation: 2704

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:

class Tournament < ActiveRecord::Base
  has_many :competitions

  def registrations
    regs = []
    self.competitions.each do |competition|
      competition.registrations.each do |registration|
        regs << registration
      end
    end
    regs
  end

  def users
    usrs = []
    self.registrations.each do |registration|
      usrs << registration.user
    end
    usrs
  end

end

Now within a view you can:

<% @tournament.users.each do |user| %>
  User: <%= user.name %><br />
<% end %>

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.

Upvotes: 2

Related Questions