# Non-association and pulling data from many models

**URL:** <https://www.ruby-forum.com/t/non-association-and-pulling-data-from-many-models/172719>\
**Category:** Rails\
**Created:** [July 26, 2009, 10:21pm UTC](https://www.ruby-forum.com/t/non-association-and-pulling-data-from-many-models/172719 "2009-07-26T22:21:58Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![elricstorm](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/da6949/32.png) [@elricstorm](https://www.ruby-forum.com/u/elricstorm)\
**Post date:** [July 26, 2009, 10:21pm UTC](https://www.ruby-forum.com/t/non-association-and-pulling-data-from-many-models/172719/1 "2009-07-26T22:21:58Z")

</div>

Here is my current model with the issue:

class Virtual \< ActiveRecord::Base  
belongs\_to :team

named\_scope :compiled\_this\_week, lambda { { :conditions =\>  
[‘created\_at \> ? and created\_at \< ?’, Time.now.beginning\_of\_week,  
Time.now.end\_of\_week] } }

def self.pullstats(model, teamone)  
model.find(:all, :conditions =\> [‘team\_id = ?’, teamone], :order =\>  
:team\_id)  
end

def self.start(teamone, teamtwo)  
nameone = Team.find(teamone)  
nametwo = Team.find(teamtwo)  
rushone = compiled\_this\_week.pullstats(RushingOffense, teamone)  
rushtwo = compiled\_this\_week.pullstats(RushingOffense, teamtwo)  
passone = compiled\_this\_week.pullstats(PassingOffense, teamone)  
passtwo = compiled\_this\_week.pullstats(PassingOffense, teamtwo)  
return nameone, nametwo, rushone, rushtwo, passone, passtwo  
end

end

My current test uses:

a,b,c,d,e,f = Virtual.start(10,12)

10 and 12 are IDs for different teams.  
a = team model for team 10  
b = team model for team 12  
c = rush model for team 10  
d = rush model for team 12  
e = rush model for team 10  
f = pass model for team 12

The test will pass and data can be pulled and I can view the data using  
var.fieldname etc. to show the data comparisons between both teams.  
However, I know this has got to be a very long way of doing things.

Normally I would try to use a :joins statement and plop each table side  
by side to one another and then just pull the respective fields. Only,  
I don’t think I can do that with my current model.

Virtual Model has (no data) and the controller is just being used for  
grabbing data. I have a total of 37 tables and I’m just not certain how  
to pull the data without doing something as clunky as what I’m doing.

From what I understand, I can only do a :joins from a model that  
belongs\_to another model… i.e. RushingOffense belongs\_to :team so I can  
do RushingOffense.find(:all, :joins =\> [:team]) but I can’t do  
Team.find(:all, :joins =\> [:rushing\_offense]). If I try the latter I’ll  
get an error about not finding an association.

I setup my data so that all my data tables belong\_to team and team has  
many data tables. I just want to do a side by side comparison of two  
teams. What is the best way to accomplish this?

Should I move away from the virtual controller and go back to the teams  
controller and create a specific view and reference everything from  
there? Or, should I continue with the clunky way I’m doing it now…?

---

<div class="post-metadata">

**Author:** ![elricstorm](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/da6949/32.png) [@elricstorm](https://www.ruby-forum.com/u/elricstorm)\
**Post date:** [July 26, 2009, 11:02pm UTC](https://www.ruby-forum.com/t/non-association-and-pulling-data-from-many-models/172719/2 "2009-07-26T23:02:17Z")

</div>

I suppose I could use:

def self.pullstats(model ,team, field)  
model.find(:all, :select =\> field, :conditions =\> [‘team\_id = ?’,  
team], :order =\> :team\_id)  
end

And from the controller declare my instance variables as:

@teamone\_rush = Virtual.pullstats(RushingOffense, 10, “ydspg”)  
@teamtwo\_rush = Virtual.pullstats(RushingOffense, 12, “ydspg”)  
etc.

But as you can see this would amount to (2 teams x 37 models of data  
with single column retrievals) or:

74 instance variables in the controller…

My problem is I don’t know how to associate the Virtuals controller to  
the rest of the models I want to pull the data from so that I can :join  
their respective tables to one large query…

I would rather do:

def self.pullstats(team)  
Team.find(team, :joins =\> [:rushing\_offense, :passing\_offense,  
:total\_offense, :scoring\_offense, etc. etc., :conditions =\> [‘team\_id =  
?’, team], :order =\> :team\_id)  
end

This would do side by side joins where the team\_id of each table would  
line up with the team.id of the Teams table.

How can I do the above? Anyone?

---

<div class="post-metadata">

**Author:** ![elricstorm](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/da6949/32.png) [@elricstorm](https://www.ruby-forum.com/u/elricstorm)\
**Post date:** [July 26, 2009, 11:08pm UTC](https://www.ruby-forum.com/t/non-association-and-pulling-data-from-many-models/172719/3 "2009-07-26T23:08:51Z")

</div>

I figured it out - will post my response in a moment in case someone  
reads and tries to respond.

---

<div class="post-metadata">

**Author:** ![elricstorm](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/da6949/32.png) [@elricstorm](https://www.ruby-forum.com/u/elricstorm)\
**Post date:** [July 26, 2009, 11:16pm UTC](https://www.ruby-forum.com/t/non-association-and-pulling-data-from-many-models/172719/4 "2009-07-26T23:16:42Z")

</div>

Okay, here was my issue in detail.

Because I have 37 controllers/models, I needed to make it easier for me  
to manage them. So I performed a lot of inheritance. But, I forgot to  
add true associations.

Example Controller:

class UniversalTemplatesController \< ApplicationController

# contains all functions for all 37 controllers

end

class RushingOffensesController \< UniversalTemplatesController

# contains only an authenticate routine - nothing else

end

etc. etc. for the next 36 controllers

Example Model:

class InheritanceTemplate \< ActiveRecord::Base  
self.abstract\_class = true

# contains all methods that other 37 models need

end

class RushingOffense \< InheritanceTemplate

# I forgot to put my associations in here

# Instead I put them in the InheritanceTemplate model

# thinking they would inherit - untrue

# Correction is below

belongs\_to :team  
end

etc. etc. for the other 36 models

class Team \< ActiveRecord::Base

# I did have has\_many :inheritance\_templates

# This was wrong

# Correction below

has\_many :rushing\_offenses  
has\_many :passing\_offenses  
etc. etc.  
end

Now I can do:

Team.all :join =\> [:rushing\_offense, :passing\_offense]  
etc.

I can’t believe I made this simple mistake. I guess it happens when you  
have so many models/controllers and are working on a large project.

---

<div class="post-metadata">

**Author:** ![elricstorm](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/da6949/32.png) [@elricstorm](https://www.ruby-forum.com/u/elricstorm)\
**Post date:** [July 27, 2009, 12:06am UTC](https://www.ruby-forum.com/t/non-association-and-pulling-data-from-many-models/172719/5 "2009-07-27T00:06:04Z")

</div>

Well large queries are one thing but this is probably too large:

def self.start(teamone, teamtwo)  
Team.find(teamone,teamtwo, :joins =\> [ :tsrs\_ratings,  
:rushing\_offenses, :passing\_offenses, :scoring\_offenses,  
:total\_offenses, :red\_zone\_offenses, :fumbles\_losts,  
:passes\_had\_intercepteds, :turnovers\_losts, :sacks\_alloweds,  
:tackles\_for\_loss\_alloweds, :passing\_efficiencies,  
:first\_downs\_offenses, :third\_down\_conversion\_percentages,  
:fourth\_down\_conversion\_percentages, :total\_defenses,  
:rushing\_defenses, :pass\_defenses, :scoring\_defenses,  
:red\_zone\_defenses, :fumbles\_recovereds,  
:passes\_intercepteds, :turnovers\_gaineds, :sacks,  
:tackles\_for\_losses, :pass\_efficiency\_defenses, :first\_downs\_defenses,  
:third\_down\_percentage\_defenses,  
:fourth\_down\_percentage\_defenses, :kickoff\_returns,  
:punt\_returns, :net\_puntings, :kickoff\_return\_yardage\_defenses,  
:punt\_return\_yardage\_defenses, :turnover\_margins ])  
end

I only need to select specific fields in each of those tables but how  
would I go about using :select =\> with this? In order of which tables  
are grabbed/referenced?

:joins =\> 1,2,3,4,5 etc…  
:select =\> “1”, “2”, “3”, “4”, “5” etc.

?

And, my data has weekly compiled but my teams table does not. My Teams  
table is static and untouched and contains exactly 120 teams. My other  
data tables could contain up to 16 weeks worth of data.

I usually use a scope or condition to pull the data based on:

named\_scope :compiled\_this\_week, lambda { { :conditions =\>  
[‘created\_at \> ? and created\_at \< ?’, Time.now.beginning\_of\_week,  
Time.now.end\_of\_week] } }

But, it’s either going to be ambiguous in this case or it won’t work  
because the created\_at won’t apply to teams. Any tips/pointers for how  
to get past this particular piece?

I’m only posting rebuttals to mark my progress but I see no one  
answering or commenting on my threads so either I’m asking too much, or  
giving too much information, the latter which I always thought was  
better when asking questions.

---

<div class="post-metadata">

**Author:** ![elricstorm](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/da6949/32.png) [@elricstorm](https://www.ruby-forum.com/u/elricstorm)\
**Post date:** [July 27, 2009, 1:03am UTC](https://www.ruby-forum.com/t/non-association-and-pulling-data-from-many-models/172719/6 "2009-07-27T01:03:30Z")

</div>

Okay breaking everything posted in this topic down to one question only:

Look at the following:

def self.start(teamone, teamtwo)  
week\_start\_date  
=Time.now.beginning\_of\_week.to\_date.strftime(’%Y-%m-%d’)  
week\_end\_date = Time.now.end\_of\_week.to\_date.strftime(’%Y-%m-%d’)  
compiled\_on = week\_start\_date…week\_end\_date  
Team.find( teamone, teamtwo,  
:joins =\> [:tsrs\_ratings, :rushing\_offenses],  
:conditions =\> { :tsrs\_ratings =\> {:compiled\_on =\> compiled\_on},  
:rushing\_offenses =\> {:compiled\_on =\> compiled\_on} },  
:select =\> “name, tsrs\_ratings.tsrs, rushing\_offenses.ydspg”,  
:order =\> “tsrs\_ratings.team\_id” )  
end

Everything about this works fine except for the select option. I want  
to select name from the teams table, tsrs from the tsrs\_ratings table,  
and ydspg from the rushing\_offenses table.

How do I combine a multiple select from different tables?

If I have the answer to this question I think I’m going to be just  
dandy.

Thanks!

---

<div class="post-metadata">

**Author:** ![elricstorm](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/da6949/32.png) [@elricstorm](https://www.ruby-forum.com/u/elricstorm)\
**Post date:** [July 27, 2009, 2:35am UTC](https://www.ruby-forum.com/t/non-association-and-pulling-data-from-many-models/172719/7 "2009-07-27T02:35:26Z")

</div>

Okay, this doesn’t make any sense. This should work:

def self.start(teamone, teamtwo)

week\_start\_date  
=Time.now.beginning\_of\_week.to\_date.strftime(’%Y-%m-%d’)  
week\_end\_date = Time.now.end\_of\_week.to\_date.strftime(’%Y-%m-%d’)  
compiled\_on = week\_start\_date…week\_end\_date  
Team.find( teamone, teamtwo,  
:select =\> “teams.name, tsrs\_ratings.tsrs, rushing\_offenses.ydspg”,  
:joins =\> [:tsrs\_ratings, :rushing\_offenses],  
:conditions =\> { :tsrs\_ratings =\> {:compiled\_on =\> compiled\_on},  
:rushing\_offenses =\> {:compiled\_on =\> compiled\_on} },  
:order =\> “teams.id” )

end

SQL returns (from development.log):

SELECT teams.name, tsrs\_ratings.tsrs, rushing\_offenses.ydspg  
FROM `teams`  
INNER JOIN `tsrs_ratings` ON tsrs\_ratings.team\_id = teams.id  
INNER JOIN `rushing_offenses` ON rushing\_offenses.team\_id = teams.id  
WHERE (`teams`.`id` IN (10,12) AND (`tsrs_ratings`.`compiled_on` BETWEEN  
‘2009-07-20’ AND ‘2009-07-26’ AND `rushing_offenses`.`compiled_on`  
BETWEEN ‘2009-07-20’ AND ‘2009-07-26’)) ORDER BY teams.id

If I take the same sql statement returned from the development log and  
place into mysql directly I get:

name tsrs ydspg  
Florida 112.005 231.14  
TCU 99.0148 220.23

Yet if I try to reference it in rails:

test = Virtual.start(10,12)

test[0]  
=\> #\<Team name: “Florida”\>

test[0].tsrs\_ratings  
=\> []

test[0].tsrs\_ratings[0]  
=\> nil

What gives??

---

<div class="post-metadata">

**Author:** ![elricstorm](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/da6949/32.png) [@elricstorm](https://www.ruby-forum.com/u/elricstorm)\
**Post date:** [July 27, 2009, 3:49am UTC](https://www.ruby-forum.com/t/non-association-and-pulling-data-from-many-models/172719/8 "2009-07-27T03:49:17Z")

</div>

Solved it on my own. 🙂

test[0].tsrs[0]

… instead of … test[0].tsrs\_ratings.tsrs[0]

---

<div class="post-metadata">

**Author:** ![elricstorm](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/da6949/32.png) [@elricstorm](https://www.ruby-forum.com/u/elricstorm)\
**Post date:** [July 27, 2009, 6:26am UTC](https://www.ruby-forum.com/t/non-association-and-pulling-data-from-many-models/172719/9 "2009-07-27T06:26:33Z")

</div>

Alpha B. wrote:

> Solved it on my own. 🙂
> 
> test[0].tsrs[0]
> 
> … instead of … test[0].tsrs\_ratings.tsrs[0]

In case someone views this with a similar issue at hand, the final fix  
was listed somewhat incorrectly.

It was supposed to read test[0].tsrs and not test[0].tsrs[0]

You can also do:

:select =\> “teams.name, tsrs\_ratings.tsrs AS newname,  
rushing\_offenses.ydspg AS anothernewname”

and then access it via, test[0].newname and test[0].anothernewname and  
since I had so many stats this worked out best.

By using such a large query and only performing one, it makes it a lot  
easier on my database.

Fyi…
