【问题标题】:Couldn't find Listing with 'id'=all, Search Form找不到“id”=all 的列表,搜索表单
【发布时间】:2014-09-11 00:48:16
【问题描述】:

所以这很奇怪。 我关注了这个 railscast http://railscasts.com/episodes/37-simple-search-form 在我实现了一切之后,它看起来像这样

index.html.erb

<%= form_tag findjobs_path, :method => 'get' do %>
      <p>
      <%= text_field_tag :search %>
      <%= submit_tag "search" %>
       </p>
<% end %>

listings_controller.rb

    def index
    @listings = Listing.all
    @listings = Listing.paginate(:page => params[:page], :per_page => 10)
    @user = User.find_by_name(params[:name])
    @listing = Listing.find_by_id(params[:id])
    @categories = Category.all
    @listings = Listing.search(params[:search])
    end
end

listing.rb

def self.search(search)
  if search
    find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
  else
    find(:all)
  end
end

我收到以下错误:找不到带有 'id'=all 的列表 我知道 find 方法会立即查找 id。 但是我不知道我需要如何设置它以便它搜索我的所有列表。 find_by_all 当然不起作用。

希望大家帮忙

非常感谢你

【问题讨论】:

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


    【解决方案1】:

    修改listing.rb search方法怎么样?

    def self.search(search)
      if search
        self.where("name like ?", "%#{search}%")
      else
        self.all
      end
    end
    

    加号..

    listings_controller.rb

    def index
      @listings = Listing.all 
      # Patching all Listing
    
      @listing = Listing.where(id: params[:id]) if params[:id].present?
      # Find By Id (For pagination, the 'where' statement result is Listing ActiveRecord::Relationship )
      @listings = @listings.search(params[:search]) if params[:search].present?
      # Search using Keyword
      @listings = @listings.paginate(:page => params[:page], :per_page => 10)
      # Pagination
      @user = User.find_by_name(params[:name]) if params[:name].present?
      # Find User using name column
      @categories = Category.all
    
    end
    

    【讨论】:

    • 我更改了它,但我的分页出现了一个非常令人困惑的错误。当我尝试自己修改搜索时,我也遇到了这个错误。这是新的错误:#<:activerecord_relation:0x49176a8> 的未定义方法 `total_pages' 它指向此代码
    • @Rika listing_controller.rb 也请修改 :)
    • @Rika:潜在的问题是您将古老的 Rails2 代码与 Rails4 一起使用。 Model.find(:all) 不适用于 Rails4,并且 (AFAIK) 在 Rails3 中已弃用。您需要更多最新的教程材料。
    • 非常感谢大家!这超出了我的要求。所以现在搜索工作并查找列表名称。我需要做些什么不同的事情才能让它通过列表的名称、描述和位置进行搜索?
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签