我在 rails 2.3.8 和 will_paginate 插件上使用 ruby。
我刚刚注意到,如果我写这样的东西:
Announcement.paginate :page => params[:page], :per_page => 10, :conditions => some_condition
它会起作用的。
但是,如果我写这样的东西:
announcements = Announcement.all :conditions => some_condition
@ann = announcements.paginate :page => params[:page], :per_page => 10
它不会识别条件。
编辑:
我开发了一个搜索功能,并且由于我必须实现一个排序功能,我必须将搜索功能放在模型的方法中,以便每次我需要搜索或按某个字段排序时从控制器调用它。
因此,我的模型的方法如下所示:
def self.search_by_relevance(words)
conditions = get_search_conditions(words)
Announcement.published.descend_by_featured.order_by_rate :conditions => conditions
end
其中“published”和“order_by_rate”被命名为范围,“descend_by_feature”属于“searchlogic”gem。
def self.get_search_conditions(words)
unless words.empty? or words.nil?
conditions = ''
words.each do |word|
if conditions.nil? or conditions.empty?
conditions = '(title like "%' + word + '%" or description like "%' + word + '%")'
else
conditions += ' and (title like "%' + word + '%" or description like "%' + word + '%")'
end
end
conditions
end
end
我的控制器的动作如下所示:
def search
@announcements = Announcement.search_by_relevance(params[:txtSearch].to_s.split).paginate :page => params[:page], :per_page => 10 unless params[:txtSearch].nil? or params[:txtSearch].empty?
end
此语法无法识别模型方法中指定的条件。
编辑2:
感谢您的帖子。再测试一下我的代码,我发现如果我在这一行的“order_by_rate”之后写“.all” Announcement.published.descend_by_featured.order_by_rate :conditions => conditions
,在 search_by_relevance 方法中它将返回正确的查询,但是 will_paginate 插件会给我以下错误(只要我添加“。全部”):
NoMethodError in AnnouncementsController#search
undefined method `to_i' for {:page=>nil, :per_page=>10}:Hash
D:/Proyectos/Cursometro/www/vendor/plugins/will_paginate/lib/will_paginate/collection.rb:15:in `initialize'
D:/Proyectos/Cursometro/www/vendor/plugins/will_paginate/lib/will_paginate/core_ext.rb:37:in `new'
D:/Proyectos/Cursometro/www/vendor/plugins/will_paginate/lib/will_paginate/core_ext.rb:37:in `paginate'
D:/Proyectos/Cursometro/www/app/controllers/announcements_controller.rb:276:in `search'
首先,我不明白为什么我必须将“.all”添加到查询中才能正常工作,其次,我不明白为什么当我包含“.all”时 will_paginate 不起作用(我也尝试添加以下代码但没有用:):page => params[:page] || 1
。
此外,如果我在查询中包含“.all”语法,它将返回:
SELECT * FROM
announcements
WHERE ((title like "%anuncio%" or description like "%anuncio%")) AND (announcements.state = 'published') ORDER BY Advertisements.featured DESC
如果我不这样做,它将返回:
SELECT * FROM
announcements
WHERE (announcements.state = 'published') ORDER BY Advertisements.featured DESC
您是否看到最后一个条件中没有包含任何条件?这导致了问题。