模型关系问题
我正在尝试根据以下模型关联计算类别中所有条目的平均(平均)评级...
class Entry < ActiveRecord::Base
acts_as_rateable
belongs_to :category
...
end
class Category < ActiveRecord::Base
has_many :entry
...
end
class Rating < ActiveRecord::Base
belongs_to :rateable, :polymorphic => true
...
end
评级模型由 充当可评级插件,因此可评级模型如下所示...
module Rateable #:nodoc:
...
module ClassMethods
def acts_as_rateable
has_many :ratings, :as => :rateable, :dependent => :destroy
...
end
end
...
end
我如何执行平均计算?这可以通过 Rails 模型关联来完成还是必须求助于 SQL 查询?
I am trying to calculate the average (mean) rating for all entries within a category based on the following model associations ...
class Entry < ActiveRecord::Base
acts_as_rateable
belongs_to :category
...
end
class Category < ActiveRecord::Base
has_many :entry
...
end
class Rating < ActiveRecord::Base
belongs_to :rateable, :polymorphic => true
...
end
The rating model is handled by the acts as rateable plugin, so the rateable model looks like this ...
module Rateable #:nodoc:
...
module ClassMethods
def acts_as_rateable
has_many :ratings, :as => :rateable, :dependent => :destroy
...
end
end
...
end
How can I perform the average calculation? Can this be accomplished through the rails model associations or do I have to resort to a SQL query?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
平均方法可能就是您正在寻找的方法。以下是根据您的情况使用它的方法:
The average method is probably what you're looking for. Here's how to use it in your situation:
您可以在模型上使用named_scope 或自定义方法吗?不管怎样,它仍然需要一些 SQL,因为如果我理解这个问题,你正在计算一个值。
在传统的数据库应用程序中,这将是数据表的视图。
因此,在这种情况下,您可能会做类似的事情...(注意未经过测试或确定它是 100% 完成的)
Could you use a named_scope or custom method on the model. Either way it would still require some SQL since, if I understand the question, your are calculating a value.
In a traditional database application this would be a view on the data tables.
So in this context you might do something like... (note not tested or sure it is 100% complete)
编辑 - 查看 EmFi 的修订答案。
我不做任何承诺,但试试这个
Edit - Check out EmFi's revised answer.
I make no promises but try this