Arnaud Leymet
Arnaud Leymet

Reputation: 6122

Joins associations in Rails 3

I need to count the number of views of an asset, this asset being embeded in multiple blogs, each blog generating multiple view for that asset.

UML diagram

I'm using Rails 3 and I was expecting the following to work:

class Asset < ActiveRecord::Base
  has_many :embeds
end

class Embed < ActiveRecord::Base
  belongs_to :asset
  has_many :views
end

class View < ActiveRecord::Base
  belongs_to :embed
end

class Assets < ApplicationController
  def show
    asset = Asset.find_by_id(params[:id])
    @views = asset.embeds.views.count
  end
end

Of course, it didn't work as expected. Why is that?

And what would be the best approach to this? (joins, includes, raw SQL...)

Upvotes: 0

Views: 276

Answers (1)

mnelson
mnelson

Reputation: 3012

All you need is a has_many :through

class Asset < ActiveRecord::Base
  has_many :embeds
  has_many :views, :through => :embeds
end

Then you just do this:

@views = asset.views.size

Upvotes: 1

Related Questions