Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails搜索的重复结果(Railscast#111)_Ruby On Rails - Fatal编程技术网

Ruby on rails Rails搜索的重复结果(Railscast#111)

Ruby on rails Rails搜索的重复结果(Railscast#111),ruby-on-rails,Ruby On Rails,我从Railscast#111(高级搜索)执行搜索时,得到了一个奇怪的结果 从我的条目来看,搜索结果是正常的,但是当结果大于1时(Iv'e只测试了两个结果),结果会加倍。因此,当我期望得到两个结果时,我得到了4(在表中渲染) 奇怪的是,当我期望1个结果时,它只呈现1个结果 我感觉它与我的“Search.rb”文件有关,该文件给出了搜索参数。其他人能解释一下为什么这会产生重复的结果吗 class Search < ActiveRecord::Base def entries @e

我从Railscast#111(高级搜索)执行搜索时,得到了一个奇怪的结果

从我的条目来看,搜索结果是正常的,但是当结果大于1时(Iv'e只测试了两个结果),结果会加倍。因此,当我期望得到两个结果时,我得到了4(在表中渲染)

奇怪的是,当我期望1个结果时,它只呈现1个结果

我感觉它与我的“Search.rb”文件有关,该文件给出了搜索参数。其他人能解释一下为什么这会产生重复的结果吗

class Search < ActiveRecord::Base
  def entries
    @entries ||= find_entries
  end

private

  def find_entries
    entries = Entry.order(:firstname)
    entries = entries.where("firstname like ?", "%#{firstname}%") if firstname.present?
    entries = entries.where("lastname like ?", "%#{lastname}%") if lastname.present?
    entries
  end
end
类搜索
我正在按firstname或lastname搜索,但条目中有更多字段。

试试看

def find_entries
    entries = Entry.order(:firstname)
    if !firstname.blank?
        entries = entries.where("firstname like ?", "%#{firstname}%")
        if !lastname.blank?
            entries = entries.where("lastname like ?", "%#{lastname}%")
        end
    else
        if !lastname.blank?
            entries = entries.where("lastname like ?", "%#{lastname}%")
        end
    end
    entries
end

你确定没有在视图中显示它们两次吗?我是这么想的,但是为什么当它返回一个结果时只显示一个结果,而当它是多个结果时,则会重复它们我的意见是,第一个在哪里检索两条记录,然后第二个在哪里也检索两条记录以尝试调试SQL,您可以使用
#to_sql
条目。to_sql
谢谢mate-问题似乎在视图中-我的表是根据结果的数量呈现的。这看起来对吗:其实不用担心,我知道了。我的show.html.erb使用了行'entry',:collection=>@search.entries%>来呈现重复的行-我刚刚说了,解决了这个问题-谢谢你的帮助