I am working on a rails project for a while and I juste encountered (what I think is) a small problem.
To make it simple, I have 3 model like this:
class House < ActiveRecord::Base
has_many :house_style_relationships
end
class HouseStyleRelationship < ActiveRecord::Base
attr_accessible :percentage
belongs_to :style
belongs_to :house
end
class Style < ActiveRecord::Base
has_many :house_style_relationships
end
So the HouseStyleRelationship model simply let us know the style percentage of an House.
For example an House can be 70% Modern and 30% Classic.
What I need to do is to get the average of each styles for all the houses.
To do that I used this working query under SQLite:
houses_count = Houses.count
HouseStyleRelationship.joins(:style).select("style.name, SUM(house_style_relationships.percentage)/#{houses_count} as percentage").group("styles.id")
But when I decided to push all this stuff on Heroku, I got a problem with PostgreSQL.
In fact, to create an HouseStyleRelationship object (I don’t even need), ActiveRecord ask for a HouseStyleRelationship.id which make the Group By crashing (with the query).
(PostgreSQL don’t want to group records with different ids)
Do you have a solution to prevent ActiveRecord to generate model instances as answer and so remove the HouseStyleRelationship.id from the query ?
(I can’t use SELECT DISTINCT since I need the SUM() calculation)
Thanks in advance !
You need to create your join table such that it has no primary key. The create_table statement in your migration should look something like this.