Activerecord 从DB中获取排名靠前的模型的排序列表
使用:Rails 4.1.4、PostgreSQL 9.1.13 嗨。我有一个简单的问题,但由于某种原因我无法完成。图片如下: 型号Activerecord 从DB中获取排名靠前的模型的排序列表,activerecord,ruby-on-rails-4,Activerecord,Ruby On Rails 4,使用:Rails 4.1.4、PostgreSQL 9.1.13 嗨。我有一个简单的问题,但由于某种原因我无法完成。图片如下: 型号 class Article < ActiveRecord::Base belongs_to :user has_many :votes end class User < ActiveRecord::Base has_many :articles has_many :votes end class Vote < Active
class Article < ActiveRecord::Base
belongs_to :user
has_many :votes
end
class User < ActiveRecord::Base
has_many :articles
has_many :votes
end
class Vote < ActiveRecord::Base
belongs_to :article
belongs_to :user, scope: :hotel_id
validates_inclusion_of :value, in: 0..5
validates_uniqueness_of :user_id, :article_id
end
问题是,我无法向数据库写入正确的查询,该数据库将:1)查找文章,2)查找每篇文章的所有投票,3)对相应文章投票的所有值求和,4)对它们进行排序(这一步我知道怎么做)
感谢您的阅读和帮助
p.S.也许我解决问题的方法几乎是错的。如果是这样的话,请告诉我正确的答案。好的,我自己做的。如果有人遇到同样的问题,这里有一个解决方案 1.投票模型中总结投票的价值:
def self.sum_value
sum(:value)
end
2.将新属性(和列)添加到文章-user\u rating:integer
3.在文章模型中定义了两个类方法:
# assign user_rating attribute with the sum of all votes values
def set_user_rating
user_rating = self.votes.sum_value
self.update_attribute(:user_rating, user_rating)
end
# get top 5 articles by user_rating value from db
def self.top_by_user_rating
Article.order(:user_rating).reverse_order.limit(5)
end
4.在ArticlesController
defineshowcase
操作中:
def showcase
@top_articles = Article.top_by_user_rating
end
def create
@article = Article.find(params[:article_id])
@vote = @article.votes.create(vote_params)
if @vote.save
@article.set_user_rating
redirect_to @article, notice: "Thanks for your vote"
else
.
end
end
5。在VotesController
definecreate
操作中:
def showcase
@top_articles = Article.top_by_user_rating
end
def create
@article = Article.find(params[:article_id])
@vote = @article.votes.create(vote_params)
if @vote.save
@article.set_user_rating
redirect_to @article, notice: "Thanks for your vote"
else
.
end
end
它工作正常,测试正在通过