2011-03-24 30 views
0

我需要計算資產的視圖數量,這個資產被嵌入到多個博客中,每個博客都會爲該資產生成多個視圖。在Rails 3中加入社團

UML diagram

我使用的Rails 3,我期待下面的工作:

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 

當然,它並沒有達到預期效果。這是爲什麼?

什麼是最好的方法呢? (連接,包括原始的SQL ...)

回答

1

所有你需要的是一個的has_many:通過

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

然後你只是這樣做:

@views = asset.views.size 
+0

這就是它!這個解決方案可以很好地工作。 – 2011-03-24 18:58:16