如何实现简单的搜索表单与分页结合使用?
我正在关注 Ryan Bates 的铁路广播: http://railscasts.com/episodes/37-simple -搜索表单 解决我在带有 will-paginate 的页面上搜索结果的问题。
在这里他回答了如何解决这个问题的问题。然而,我已经尝试过,但没有任何运气。根据他的第二个解决方案,我得到了“search_conditions”的 NoMethod 错误作为结果。
代码:
projects/index.rhtml
<% form_tag projects_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
projects_controller.rb
def index
@projects = Project.search(params[:search])
end
models/project.rb
def self.search(search)
if search
find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
else
find(:all)
end
end
他的答案:
一种方法是调用类方法“search_conditions”,而不是让它执行查找,它只会返回一个条件数组,以便您可以在分页方法中使用它。
Course.paginate(:all, :conditions => Course.search_conditions(..))
另一种方法是调用方法“pagination_search”并让它调用“paginate”而不是“find”。
最后,您可以让搜索方法接受一个使用 with_scope 来设置查找条件的块。这样您就可以在该块中调用“分页”,并且条件将自动应用。
有人可以向我解释我应该如何解决这个问题吗?我是 Rails 新手,也许我只是误解了他的意思。
I am following Ryan Bates' railcasts: http://railscasts.com/episodes/37-simple-search-form
in solving my issue with the search results on a page with will-paginate.
Here he answers the question as to how to solve this problem. However, I've tried them and haven't had any luck. From following his second resolution, I get a NoMethod error for "search_conditions" as the result.
The Code:
projects/index.rhtml
<% form_tag projects_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
projects_controller.rb
def index
@projects = Project.search(params[:search])
end
models/project.rb
def self.search(search)
if search
find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
else
find(:all)
end
end
His Answers:
One way is to call the class method "search_conditions" and instead of having it do the find it will just return a conditions array so you could use it in the paginate method.
Course.paginate(:all, :conditions => Course.search_conditions(..))
Another is to call the method "paginated_search" and have it call "paginate" instead of "find".
Lastly you could have the search method accept a block which uses with_scope to set the find conditions. This way you could call "paginate" in that block and the conditions will automatically be applied.
Can someone explain to me how I should go about solving this? I am new to rails and maybe I am just misunderstanding what he is saying.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您关注的 Railscast 已经很老了,从那时起发生了很多变化。尝试更改
search
方法的实现,如下所示:以及控制器中的类似内容:
Railscast you following is pretty old, lots changed since then. Try to change implementation of
search
method like this:and something like this in controller: