ActiveRecord query for related elements

I have a Solutions model, with has_many Reviews, and Reviews with 'has_many' ReviewValues. Each ReviewValue is also linked to a Tag which contains the tag name. I'm trying to select the avarage scores (for all the Tags so grouped by tag) that go with a particular solution.

Basically the Reviews model is the join table between Solutions and ReviewValues (and there's also the Tags table which contains the names)

What I have so far is this:

@total = self.reviews.review_values.average(:score)

The problem is that I can only call review_values on one specific review and not for all of them. so I'd have to do something like self.reviews.first.review_values...which doesn't help me because I need the average for each reviewvalue (by Tag name)

This is what the review_values table looks like:

Table review_values
===================
id, tag_id, review_id, score, created_at, updated_at
-------------------
id               int(11) PK
tag_id           int(11)
review_id        int(11)
score            int(11)
created_at       datetime
updated_at       datetime

And the tags table:

Table tags
==========
id, name
----------
id               int(11) PK
name             varchar(255)

Answers


Have you tried using :through ? eg:

class Solution
    has_many :reviews
    has_many :review_values, :through => :reviews
end

@total = my_solution.review_values.average(:score)

Need Your Help

PHP Generate random numbers as array shows (by click a selection box)

php mysql arrays for-loop

I am beginner of studying PHP and I started to study the Looping and array by using PHP with Mysql. Now I met a problem which is generate random numbers as array, based on the amount of random numb...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.