Rails没有在搜索表单上传递DB Query

时间:2016-08-30 14:21:29

标签: mysql ruby-on-rails search

这里看起来更好看,这是日志,它传递了param,但它没有传递带有该参数的查询

Started GET "/items?utf8=%E2%9C%93&search=blanca" for 65.34.251.106 at 2016-08-30 03:55:51 +0000
Processing by ItemsController#index as HTML
Parameters: {"utf8"=>"✓", "search"=>"blanca"}
User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1  [["id", 3]]
Item Load (0.3ms)  SELECT  "items".* FROM "items" LIMIT 50 OFFSET 0
Item Load (0.2ms)  SELECT  "items".* FROM "items"  ORDER BY "items"."id" ASC LIMIT 1 OFFSET 0
Rendered items/_items.html.erb (3.2ms)
Rendered items/index.html.erb within layouts/application (4.9ms)

这是控制器:

def index
 @items = Item.search(params[:search])
end

这是模型:

 class Item < ActiveRecord::Base
  has_many :stocks
  attr_accessible :nombre, :espesor, :material, :quantity
  accepts_nested_attributes_for :stocks
   attr_accessible :stocks_attributes
   self.per_page = 50
   #  def self.search(search)
   #     Item.where("nombre LIKE ?", "%#{search}%")

   #  end

    def self.search(search_term)
    where("nombre LIKE ?", "%#{search_term}%")
    end

    protected
    end

和视图中的搜索表单:

<%= form_tag items_path, :method => 'get', :id => "items_search" do %>
 <p>
  <%= text_field_tag :search, params[:search], class: "form-control" %>
  <%= submit_tag "Search", :name => nil, class: "btn btn-danger" %>
 </p>

<div id="items"><%= render 'items' %>
</div>
<% end %> 

我有一个_items.html.erb文件,其中包含要呈现的项目,该部分有效,因为无论我在搜索栏上的输入,它总是显示所有项目

当我尝试在控制台中使用.search方法时,这是输出

 2.3.0 :041 > Item.search("blanca")
 NoMethodError: undefined method `search' for #<Class:0x0000000203fc58>
    from /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-     4.2.6/lib/active_record/dynamic_matchers.rb:26:in `method_missing'
      from (irb):41
    from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands/console.rb:110:in `start'
    from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands/console.rb:9:in `start'
    from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:68:in `console'
    from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
    from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands.rb:17:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

1 个答案:

答案 0 :(得分:1)

您确定在search中定义了类方法item.rb吗?导致错误说明search类没有定义Item方法。但是,请尝试以下方法为您服务。

您只想搜索表单是否正在提交。您可以使用present?方法了解搜索字词是否实际通过。

将您的控制器修改为

def index
  @items = params[:search].present? ? Item.search(params[:search]) : Item.all
end

请注意,对象只有present非空白。这很方便,因为如果有人在表单中输入“”,则不应在nombre字段中搜索空格,而是显示items表中的所有记录。

如果表单未提交,则会执行Item.all

将您的班级方法修改为

def self.search(search_term)
  where("nombre LIKE ?", "%#{search_term}%")
end

您不需要Item.where,因为类Item是调用where方法的当前上下文。请注意,我已将模式更改为%#{search_term}%,因为您并不总是希望匹配以某种模式结尾的字符串。

希望这有帮助!