【问题标题】:Search User inputted string in rails在rails中搜索用户输入的字符串
【发布时间】:2015-03-10 11:17:46
【问题描述】:

我正在尝试实现一个简单的字符串搜索。我有一个 Book 模型,它有 bookname、isbn、authname 作为属性。我在 index.html.haml 的末尾添加了这个,以允许用户使用 isbn 搜索一本书。

=form_tag({controller: "books_controller", action: "searchbook"}, :method => :get) do
  .search_field
    =text_field_tag :q
    =button_tag 'Go' , class: 'search-button' , type: :submit
%br

将此添加到我的 book_controller.rb

def searchbook
    @searchedbook = Book.where(isbn: q)
end

将此添加到我的路线文件中:

Rails.application.routes.draw do
  resources :courses

  resources :books

  get 'books_controller/searchbook' => 'books_controller#searchbook'
end

运行 rails 服务器后,当我转到 http://localhost:3000/books 时,我得到了所有书籍的列表。我可以看到列表末尾的输入框,当我输入一个 isbn 号码来搜索这本书时,这是我得到的错误:

uninitialized constant BooksControllerController

当我运行 rake 路线时,我会在列表中看到路线:

books_controller_searchbook GET    /books_controller/searchbook(.:format) books_controller#searchbook

我不确定那里出了什么问题。我要做的就是获取用户输入的字符串并运行 Book.where(isbn: "userinput") 查询来查找这本书。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 ruby-on-rails-4.1


    【解决方案1】:

    看看有什么错误uninitialized constant BooksControllerController,这意味着它已经知道'books'是一个控制器,但是你指定了books_controller所以它变成了BooksControllerController

    其实不用指定控制器字符串

    试试这个

     get 'books/searchbook' => 'books#searchbook'
    

    或者

    match 'searchbook', to: 'books#searchbook', via: :get
    

    【讨论】:

    • 我试过这个:get 'books/searchbook' => 'books#searchbook' 我得到了这个错误:ActionController::UrlGenerationError in Books#index No route matches {:action=>"searchbook", :controller=>"books_controller"} 当我尝试这个时:匹配'searchbook',到:'books#searchbook',通过::get 我得到这个:NoMethodError in Books#index undefined method `match' for #:0x007f9f487aaa50>
    • @neesop - 你又犯了同样的错误,在你的表单中也删除控制器字符串=form_tag({controller: "books_controller", action: "searchbook"}, :method => :get) do 使它像=form_tag({controller: "books", action: "searchbook"}, :method => :get) do
    • 是的!你完全正确。这解决了我的问题。但是现在我收到一个新错误,上面写着: NameError in BooksController#searchbook undefined local variable or method `q' for #<0x007f9f48329ad0>
    猜你喜欢
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多