使用 Rails 中的命名范围减少代码行数
我有 Rails 方法根据博客的投票对博客进行排序(acts_as_votable)。
方法是
# @allblogs will be some filtered blogs array
@fetch = []
@most_effective_votes = []
for blog in @allblogs
@most_effective_votes << [blog.id,blog.votes_for]
end
@most_effective_votes = @most_effective_votes.sort{|a,b| a[1]<=> b[1]}.Reverse
for mev in @most_effective_votes
@fetch << blog.Find(mev[0])
end
@allblogs = @fetch.Paginate(:per_page => 10,:page=>params[:page])
如何减少这么多行数并将其更改为某个命名范围。 请给一些建议。
i have rails method to sort the blogs based on their votes (acts_as_votable).
The method is
# @allblogs will be some filtered blogs array
@fetch = []
@most_effective_votes = []
for blog in @allblogs
@most_effective_votes << [blog.id,blog.votes_for]
end
@most_effective_votes = @most_effective_votes.sort{|a,b| a[1]<=> b[1]}.Reverse
for mev in @most_effective_votes
@fetch << blog.Find(mev[0])
end
@allblogs = @fetch.Paginate(:per_page => 10,:page=>params[:page])
How to reduce these many number of lines and to change this to some namedscope .
Please give some suggestions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您想要做的事情必须可以通过查询来完成,而不需要对数组进行操作。
首先,@allblogs应该是一个范围,而不是一个过滤数组。
其次,您可以使用以下命令更改您正在做的所有事情:
因此您的named_scope将是:
@fetch将是@allblogs.with_most_votes。
如果您需要更多帮助,请告诉我。
I think must of what you are trying to do can be done with a query without the need of doing operations with arrays.
First of all, @allblogs should be a scope, not a filtered array.
Second, it sames you can change all of what you were doing by using:
So your named_scope would be:
And @fetch would be @allblogs.with_most_votes.
Let me know if you need more help.