使用 Rails 中的命名范围减少代码行数

发布于 2024-12-24 16:11:47 字数 592 浏览 1 评论 0原文

我有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

辞取 2024-12-31 16:11:48

我认为您想要做的事情必须可以通过查询来完成,而不需要对数组进行操作。

首先,@allblogs应该是一个范围,而不是一个过滤数组。

其次,您可以使用以下命令更改您正在做的所有事情:

Blog.order("DESC votes_for")

因此您的named_scope将是:

class Blog < ActiveRecord::Base
    scope :with_most_votes, order("votes_for DESC")
end

@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:

Blog.order("DESC votes_for")

So your named_scope would be:

class Blog < ActiveRecord::Base
    scope :with_most_votes, order("votes_for DESC")
end

And @fetch would be @allblogs.with_most_votes.

Let me know if you need more help.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文