搜索不工作。获取所有结果而不是特定结果Ruby on Rails

时间:2015-12-17 18:26:54

标签: ruby-on-rails ruby ruby-on-rails-4 search model-view-controller

当我在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>&nbsp</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

1 个答案:

答案 0 :(得分:2)

尝试

def search
  criteria = params[:post][:search]
  @posts = Post.where('text LIKE ?', "%#{criteria}%")
end

例如:

> Post.where('text LIKE ?', '%SomeText%')
SELECT `posts`.* FROM `posts` WHERE (text LIKE '%SomeText%')

reference,第2.2节