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.
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
开发者_C百科 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...)
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
精彩评论