0

In a typical blog app if i do something like:

p = Post.order('created_at DESC').limit(10)
p.from(5)

It raises:

ActiveRecord::StatementInvalid: SQLite3::SQLException: near "5": syntax error: SELECT  "posts".* FROM 5  ORDER BY created_at DESC LIMIT 10

I'm trying to get the first five posts in an array and the five next in another array. If i use the .from() on an array it's working fine, i get the elements i want beginning from the number i selected. But if i use the .from() in a view or in a controller it will try to generate a new query instead of apply the .from() on the object/array.

My controller was doing:

@last_ten_posts = Post.order('created_at DESC').limit(10)

And the view:

@last_ten_posts.first(5).each do |post|
@last_ten_posts.from(5).each do |post|

How should i use the .from() method ?

Thanks

EDIT: @Rubyist give remember me the first way i was dealing with the posts, i'm interesting in finding why the .from() doesn't work ?

4

2 回答 2

2

from 方法不起作用,因为它用于指定将获取记录的表,因此在您的原始查询中,您正在查找表 5 中的帖子,这没有意义,因为您没有表 5 ,您有一个名为 posts not 5 的表。

有关 from 方法的更多信息 - http://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-from

您可能想要使用不同的方法,例如偏移量 - http://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-offset

first_five = Post.order('created_at DESC').limit(5)
last_five = Post.offset(5).order('created_at DESC').limit(5)
于 2013-10-28T18:54:18.967 回答
1
@last_ten_posts = Post.order('created_at DESC').limit(10)
first_five = @last_ten_posts.first(5)
last_five = @last_ten_posts.last(5)
于 2013-10-28T16:16:07.480 回答