【发布时间】:2016-03-24 08:13:05
【问题描述】:
当我在 Rails 应用程序中运行搜索帖子时,我会显示数据库中存在的所有帖子,而不是匹配的结果。
这是我的控制器搜索方法:
def search
@posts=Post.find(:all, :conditions=>['text LIKE ?', "%#{params[:search]}%"])
end
search.html.erb 是:
<table class="table table-striped" summary="All posts">
<% @posts.each do |post| %>
<tr><td> </td></tr>
<tr>
<td>Post #<%=post.id%> </td>
<td><%=post.text%></td>
<%if post.image_file_name%>
<td>
<%=image_tag post.image.url %>
</td>
<%end%>
</tr>
<tr>
<td><%= link_to("Like", {:action=>'#', :id=>post.id}, :class => 'action upvote')%></td>
</tr>
<%end%>
</table>
此外,我已经尝试将这些放入我的模型中:
scope :search, lambda {|query|
where (["text LIKE ?", "%#{query}%"])
}
def self.search(search)
if search
find(:all, :conditions=>['text' 'LIKE ?', "%#{params[:search]}%"])
else
find(:all)
end
end
但我得到相同的结果。任何人都可以解决这个问题?谢谢。
更新 1.0:
这是位于index.html.erb的搜索表单:
<%=form_for(:post, :method=>'get', :url=>{:action=>'search', :html=> {:multipart=>true}}) do |f| %>
<p>
<%=f.text_field(:text)%>
<%=submit_tag("Search")%>
</p>
<%end%>
更新 1.1
这是 Gemfile:
source 'https://rubygems.org'
gem 'rails', '4.0.0'
gem 'mysql2','~> 0.3.11'
gem 'paperclip', '~>3.0'
gem 'sass-rails', '~>4.0.0'
gem 'bootstrap-sass', '~>3.2.0.2'
gem 'autoprefixer-rails'
gem 'acts_as_votable', '~>0.10.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
gem 'therubyracer', platforms: :ruby
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 1.2'
group :doc do
gem 'sdoc', require: false
end
【问题讨论】:
-
@muistooshort 搜索功能都不起作用。但是,是的,我没有收到
ActiveRecord::RecordNotFound错误。 -
@muistooshort 我在我的问题中添加了 Gemfile
-
@muistooshort jlhonora 的答案在 IRB 中有效,但在 rails 应用程序中却不是这样。我认为搜索操作在某种程度上没有与搜索视图进行通信。
标签: ruby-on-rails ruby ruby-on-rails-4 search model-view-controller