'nil'不是用于搜索的与ActiveModel兼容的对象

时间:2013-05-13 14:45:05

标签: ruby-on-rails

好的,我能够通过搜索来克服山峰并使结果正确显示。但是,我注意到只有一个搜索选项有效。剩下的就是"' nil'不是与ActiveModel兼容的对象,它返回有效的部分路径。"即使我把编码还给老了。这很奇怪,因为我的搜索适用于种族,但对于表单的其他部分,它会返回该错误。也许一些新鲜的眼睛可以抓住罪魁祸首。

在我的高级搜索页面上澄清。如果我进行种族搜索,结果会上升。如果我做任何其他搜索,如宗教,性别,儿童等,它给出零错误。只是没有意义,搜索页面中的一个选项有效,而其余选项在所有选项都具有相同编码时都没有意义。似乎它没有找到它的用户。错误指向" 3<%= render @users%>"

show.html:

<h1>Search Results</h1>

<%= render @users %>

搜索控制器:

  def new
    @search = Search.new
  end

  def create
    @search = Search.new(params[:search])
    if @search.save
      redirect_to @search
    else
      render 'new'
    end
  end

  def show
    @search = Search.find(params[:id])
    @users = @search.users
    end

end

搜索模型:

 attr_accessible :age, :children, :ethnicity, :gender, :religion, :zip_code

  def users
    @users ||= find_users
  end

    private

  def find_users
    users = User.order(:id)
    users = users.where(gender: gender) if gender.present?
       users = users.where(zip_code: zip_code) if zip_code.present?
       users = users.where(children: children) if children.present?
       users = users.where(religion: religion) if religion.present?
       users = users.where(ethnicity: ethnicity) if ethnicity.present?
  end
end

搜索表单(底部的种族显示没有错误):

<h1>Advanced Search</h1>

<%= form_for @search do |f| %>
<div class="field">
  <%= f.label :gender %><br />
  <%= f.select :gender, ['man', 'woman'], :include_blank => true %>
</div>

  <div class="field">
    <%= f.label :zip_code %><br />
    <%= f.text_field :zip_code %>
  </div>
  <div class="field">
    <%= f.label :children %><br />
    <%= f.select :children, ['Yes, they live with me', 'I want kids now', "I want one someday", "Not for me"], :include_blank => true %>
  </div>
  <div class="field">
    <%= f.label :religion %><br />
    <%= f.select :religion, [["Agnostic", "1"], ["Atheist", "2"], ["Christian", "3"], ["Catholic", "4"], ["Buddhist", "5"], ["Hindu", "6"], ["Jewish", "7"], ["Muslim", "8"], ["Spiritual without affiliation", "9"], ["Other", "10"], ["None", "11"], ["Prefer not to say", "12"]], :include_blank => true %>
  </div>
  <div class="field">
    <%= f.label :ethnicity %><br />
    <%= f.select :ethnicity, [["Asian", "1"], ["Biracial", "2"], ["Indian", "3"], ["Hispanic/Latin", "4"], ["Middle Eastern", "5"], ["Native American", "6"], ["Pacific Islander", "7"], ["White", "8"], ["Other", "9"]], :include_blank => true %>
  </div>
  <div class="actions"><%= f.submit "Search" %></div>
<% end %>

1 个答案:

答案 0 :(得分:4)

那是因为在find_users方法结束时你需要返回数组:

def find_users
  users = User.order(:id)
  users = users.where(gender: gender) if gender.present?
  users = users.where(zip_code: zip_code) if zip_code.present?
  users = users.where(children: children) if children.present?
  users = users.where(religion: religion) if religion.present?
  users = users.where(ethnicity: ethnicity) if ethnicity.present?
  users # this line is important!
end

它仅适用于种族,因为这是最后一个,如果缺少种族,此方法将返回nil而不是用户数组。