Ruby on Rails will_pagination 一个数组

发布于 2024-10-06 04:19:37 字数 409 浏览 0 评论 0原文

我想知道是否有人可以解释如何在对象数组上使用 will_paginate

例如,在我的网站上,我有一个意见部分,用户可以在其中对意见进行评分。这是我写的一个方法来收集对意见进行评分的用户:

def agree_list
  list = OpinionRating.find_all_by_opinion_id(params[:id])
  @agree_list = []
  list.each do |r|
    user = Profile.find(r.profile_id)
    @agree_list << user
  end
end

谢谢

I was wondering if someone could explain how to use will_paginate on an array of objects?

For example, on my site I have an opinion section where users can rate the opinions. Here's a method I wrote to gather the users who have rated the opinion:

def agree_list
  list = OpinionRating.find_all_by_opinion_id(params[:id])
  @agree_list = []
  list.each do |r|
    user = Profile.find(r.profile_id)
    @agree_list << user
  end
end

Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(7

简美 2024-10-13 04:19:37

will_paginate 3.0 旨在利用 Rails 中新的 ActiveRecord::Relation 3,因此默认情况下它仅在关系上定义分页。它仍然可以与数组一起使用,但您必须告诉 Rails 需要该部分。

在您的 config/initializers 中的文件中(我使用了 will_paginate_array_fix.rb),添加此内容

require 'will_paginate/array'

然后您可以在数组上使用

my_array.paginate(:page => x, :per_page => y)

will_paginate 3.0 is designed to take advantage of the new ActiveRecord::Relation in Rails 3, so it defines paginate only on relations by default. It can still work with an array, but you have to tell rails to require that part.

In a file in your config/initializers (I used will_paginate_array_fix.rb), add this

require 'will_paginate/array'

Then you can use on arrays

my_array.paginate(:page => x, :per_page => y)
余罪 2024-10-13 04:19:37

您可以使用 Array#from 来模拟分页,但真正的问题是您根本不应该使用 Array。

这就是 ActiveRecord 关联 的用途。您应该仔细阅读该指南,如果您正在开发 Rails 应用程序,则需要了解很多有用的内容。

让我向您展示一种更好的方法来完成同样的事情:

class Profile < ActiveRecord::Base
  has_many :opinion_ratings
  has_many :opinions, :through => :opinion_ratings
end

class Opinion < ActiveRecord::Base
  has_many :opinion_ratings
end

class OpinionRating < ActiveRecord::Base
  belongs_to :opinion
  belongs_to :profile
end

重要的是您的数据库模式遵循正确的命名约定,否则这一切都会被破坏。确保您使用数据库迁移创建表,而不是这样做用手。

这些关联将在您的模型上创建助手,使搜索变得更加容易。您可以使用 named_scopescope 让 Rails 为您执行此操作,而不是迭代 OpinionRatings 列表并手动收集用户,具体取决于您是否使用 Rails 2.3 或 3.0。既然你没有具体说明,我就举两个例子。将其添加到您的 OpinionRating 类中:

2.3

named_scope :for, lambda {|id| 
  {
    :joins => :opinion,
    :conditions => {
      :opinion => { :id => id }
    }
  }
}

named_scope :agreed, :conditions => { :agree => true }
named_scope :with_profiles, :includes => :profile

3.0

scope :agreed, where(:agree => true)

def self.for(id)
  joins(:opinion).where(:opinion => { :id => id })
end

无论哪种情况,您都可以在 OpinionRatings 上调用 for(id) model 并传递给它一个 id:

2.3

@ratings = OpinionRating.agreed.for(params[:id]).with_profiles
@profiles = @ratings.collect(&:profile)

3.0

@ratings = OpinionRating.agreed.for(params[:id]).includes(:profile)
@profiles = @ratings.collect(&:profile)

所有这一切的结果是你现在可以轻松分页:

@ratings = @ratings.paginate(:page => params[:page])

Rails 4.x 的更新:或多或少相同:

scope :agreed, ->{ where agreed: true }

def self.for(id)
  joins(:opinion).where(opinion: { id: id })
end 

虽然对于较新的 Rails,我偏好使用 kaminari 进行分页:

@ratings = @ratings.page(params[:page])

You could use Array#from to simulate pagination, but the real problem here is that you shouldn't be using Array at all.

This is what ActiveRecord Associations are made for. You should read that guide carefully, there is a lot of useful stuff you will need to know if you're developing Rails applications.

Let me show you a better way of doing the same thing:

class Profile < ActiveRecord::Base
  has_many :opinion_ratings
  has_many :opinions, :through => :opinion_ratings
end

class Opinion < ActiveRecord::Base
  has_many :opinion_ratings
end

class OpinionRating < ActiveRecord::Base
  belongs_to :opinion
  belongs_to :profile
end

It's important that your database schema is following the proper naming conventions or all this will break. Make sure you're creating your tables with Database Migrations instead of doing it by hand.

These associations will create helpers on your models to make searching much easier. Instead of iterating a list of OpinionRatings and collecting the users manually, you can make Rails do this for you with the use of named_scope or scope depending on whether you're using Rails 2.3 or 3.0. Since you didn't specify, I'll give both examples. Add this to your OpinionRating class:

2.3

named_scope :for, lambda {|id| 
  {
    :joins => :opinion,
    :conditions => {
      :opinion => { :id => id }
    }
  }
}

named_scope :agreed, :conditions => { :agree => true }
named_scope :with_profiles, :includes => :profile

3.0

scope :agreed, where(:agree => true)

def self.for(id)
  joins(:opinion).where(:opinion => { :id => id })
end

In either case you can call for(id) on the OpinionRatings model and pass it an id:

2.3

@ratings = OpinionRating.agreed.for(params[:id]).with_profiles
@profiles = @ratings.collect(&:profile)

3.0

@ratings = OpinionRating.agreed.for(params[:id]).includes(:profile)
@profiles = @ratings.collect(&:profile)

The upshot of all this is that you can now easily paginate:

@ratings = @ratings.paginate(:page => params[:page])

Update for Rails 4.x: more or less the same:

scope :agreed, ->{ where agreed: true }

def self.for(id)
  joins(:opinion).where(opinion: { id: id })
end 

Although for newer Rails my preference is kaminari for pagination:

@ratings = @ratings.page(params[:page])
水中月 2024-10-13 04:19:37

gem will_paginate 将对 ActiveRecord 查询和数组进行分页。

list = OpinionRating.where(:opinion_id => params[:id]).includes(:profile).paginate(:page => params[:page])
@agree_list = list.map(&:profile)

The gem will_paginate will paginate both ActiveRecord queries and arrays.

list = OpinionRating.where(:opinion_id => params[:id]).includes(:profile).paginate(:page => params[:page])
@agree_list = list.map(&:profile)
薔薇婲 2024-10-13 04:19:37

如果您不想使用配置文件或遇到问题,您也可以确保返回 ActiveRecord::Relation 而不是数组。例如,将同意列表更改为用户 ID 列表,然后对这些 ID 执行 IN 以返回关系。

def agree_list
  list = OpinionRating.find_all_by_opinion_id(params[:id])
  @agree_id_list = []
  list.each do |r|
    user = Profile.find(r.profile_id)
    @agree_id_list << user.id
  end
  @agree_list = User.where(:id => @agree_id_list) 
end

从数据库的角度来看,这是低效的,但对于任何对 will_paginate 配置文件有问题的人来说,这是一个选项。

If you don't want to use the config file or are having trouble with it, you can also just ensure you return an ActiveRecord::Relation instead of an array. For instance, change the agree_list to be a list of user ids instead, then do an IN on those ids to return a Relation.

def agree_list
  list = OpinionRating.find_all_by_opinion_id(params[:id])
  @agree_id_list = []
  list.each do |r|
    user = Profile.find(r.profile_id)
    @agree_id_list << user.id
  end
  @agree_list = User.where(:id => @agree_id_list) 
end

This is inefficient from a database perspective, but it's an option for anybody having issues with the will_paginate config file.

宣告ˉ结束 2024-10-13 04:19:37

我利用了 Rails 协会的优势,想出了一个新方法:

def agree_list
  o = Opinion.find(params[:id])
  @agree_list = o.opinion_ratings(:conditions => {:agree => true}, :order => 'created_at DESC').paginate :page => params[:page]
rescue ActiveRecord::RecordNotFound
  redirect_to(profile_opinion_path(session[:user]))
end

在我看来,我像这样查找了个人资料:

<% @agree_list.each do |rating| %>
  <% user = Profile.find(rating.profile_id) %>
<% end %>

如果有更好的方法,请发布。我尝试在 OpinionRating 模型中使用named_scope 帮助器,但没有成功。这是我尝试过但不起作用的示例:

named_scope :with_profile, lambda {|id| { :joins => [:profile], :conditions => ['profile_id = ?', id] } }

但这看起来与使用 find 方法相同。

感谢您的所有帮助。

I took advantage of rails associations, and came up with a new method:

def agree_list
  o = Opinion.find(params[:id])
  @agree_list = o.opinion_ratings(:conditions => {:agree => true}, :order => 'created_at DESC').paginate :page => params[:page]
rescue ActiveRecord::RecordNotFound
  redirect_to(profile_opinion_path(session[:user]))
end

In my view I looked up the profile like so:

<% @agree_list.each do |rating| %>
  <% user = Profile.find(rating.profile_id) %>
<% end %>

Please post up if there's a better way to do this. I tried to use the named_scope helper in the OpinionRating model with no luck. Here's an example of what I tried, but doesn't work:

named_scope :with_profile, lambda {|id| { :joins => [:profile], :conditions => ['profile_id = ?', id] } }

That seemed like the same as using the find method though.

Thanks for all the help.

感受沵的脚步 2024-10-13 04:19:37

我正在使用 Rails 3 ruby​​ 1.9.2。另外,我刚刚启动应用程序,所以不包含 css 或样式。

安装 will_paginate:

gem install will_paginate

添加到 Gemfile 并运行包。

Controller

class DashboardController < ApplicationController
    include StructHelper

    def show
        @myData =structHelperGet.paginate(:page => params[:page])
    end

end

模块 StructHelper 查询服务,而不是数据库。
structHelperGet() 返回一个记录数组。

不确定更复杂的解决方案是否是伪造模型,或者经常获取数据并偶尔重新创建 sqllite 表并有一个真实的模型可供查询。刚刚创建我的第一个 Rails 应用程序。

查看

<div id="Data">
                <%= will_paginate @myData%>
                    <table>
                    <thead>
                    <tr>
                    <th>col 1</th>
                    <th>Col 2</th>
                    <th>Col 3</th>
                    <th>Col 4</th>
                    </tr>
                    </thead>
                    </tbody>
                    <% @myData.each do |app| %>
                        <tr>
                           <td><%=app[:col1]%> </td>
                           <td><%=app[:col2]%> </td>
                           <td><%=app[:col3]%> </td>
                           <td><%=app[:col4]%> </td>
                        </tr>

                    <% end %>
                    </tbody>
                    </table>
                <%= will_paginate @myData%>
                </div>

这将为您提供每页默认 30 行的分页。

如果您还没有阅读 http://railstutorial.org,请立即开始阅读。

I am using rails 3 ruby 1.9.2. Also, I am just starting app, so no css or styles included.

Install will_paginate:

gem install will_paginate

Add to Gemfile and run bundle.

Controller

class DashboardController < ApplicationController
    include StructHelper

    def show
        @myData =structHelperGet.paginate(:page => params[:page])
    end

end

module StructHelper queries a service, not a database.
structHelperGet() returns an array of records.

Not sure if a more sophisticated solution would be to fake a model, or to grab the data every so often and recreate a sqllite table once in a while and have a real model to query. Just creating my first rails app ever.

View

<div id="Data">
                <%= will_paginate @myData%>
                    <table>
                    <thead>
                    <tr>
                    <th>col 1</th>
                    <th>Col 2</th>
                    <th>Col 3</th>
                    <th>Col 4</th>
                    </tr>
                    </thead>
                    </tbody>
                    <% @myData.each do |app| %>
                        <tr>
                           <td><%=app[:col1]%> </td>
                           <td><%=app[:col2]%> </td>
                           <td><%=app[:col3]%> </td>
                           <td><%=app[:col4]%> </td>
                        </tr>

                    <% end %>
                    </tbody>
                    </table>
                <%= will_paginate @myData%>
                </div>

This will give you pagnation of the default 30 rows per page.

If you have not read http://railstutorial.org yet, start reading it now.

娇妻 2024-10-13 04:19:37

即使没有任何 gem,你也可以实现分页。我看到了这个 如何对数组进行分页?。 kaminari gems 文档中的简单实现。请参阅我从 kaminari gems 文档获得的以下示例

arr = (1..100).to_a
page, per_page = 1, 10
arr[((page - 1) * per_page)...(page * per_page)] #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
page, per_page = 2, 10
arr[((page - 1) * per_page)...(page * per_page)] #=> [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

You can implement pagination even without any gem.I saw this How do I paginate an Array?. Simple implementation in kaminari gems doc. Please see the below example which i got from kaminari gems doc

arr = (1..100).to_a
page, per_page = 1, 10
arr[((page - 1) * per_page)...(page * per_page)] #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
page, per_page = 2, 10
arr[((page - 1) * per_page)...(page * per_page)] #=> [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文