自定义搜索belongs_to关联是空的

时间:2017-04-04 10:41:22

标签: ruby-on-rails search activerecord

抱歉,这可能很简单,但它让我把头撞在墙上!

我创建了自己的搜索模型和控制器,但无法搜索belongs_to关联。我能够很好地搜索has_and_belongs_to_many关联,但是对于belongs_to我得到零结果。

# models/user.rb
class User < ApplicationRecord
  belongs_to :city

  has_and_belongs_to_many :sports
  has_and_belongs_to_many :goals
end

# models/search.rb
class Search < ApplicationRecord
  def search_users
    users = User.all
# These two work
    users = users.joins(:sports).where("sports.name ILIKE ?", "%#{sports}%") if sports.present?
    users = users.joins(:goals).where("goals.name ILIKE ?", "%#{goals}%") if goals.present?

# This doesn't
    users = users.joins(:city).where("cities.name ILIKE ?", "%#{cities}") if cities.present?

    return users
  end
end

# searches_controller.rb
class SearchesController < ApplicationController
  def new
    @search = Search.new
    @sports = Sport.uniq.pluck(:name)
    @goals = Goal.uniq.pluck(:name)
    @cities = City.uniq.pluck(:name)
  end

  def create
    @search = Search.create(search_params)
    redirect_to @search
  end

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

  private
  def search_params
    params.require(:search).permit(:sports, :goals, :gyms, :cities)
  end
end

和我的观点:

#searches/new.html.erb
<%= simple_form_for @search do |search| %>
  <%= search.label :sports %>
  <%= search.select :sports, options_for_select(@sports), include_blank: :true %>

  <%= search.label :goals %>
  <%= search.select :goals, options_for_select(@goals), include_blank: :true %>


  <%= search.input :cities, collection: City.all.order(name: :asc), as: :select, label: "City" %>

  <%= submit_tag "Search" %>
<% end %>

的搜索/ show.html.erb

<% if @search.search_users.empty? %>
  Nothing
<% else %>

  <% @search.search_users.each do |user| %>
    <%= user.first_name + ' ' + user.last_name %>

  <% end %>

<% end %>

基本上从下拉列表中选择一个城市它没有注册并给我空搜索条件,我无法弄清楚为什么它不会选择它。然而,选择体育和/或目标,它给了我匹配的用户。

提前致谢!

修改

好的,我已经设法通过在我的视图中更改我的下拉选择来实现它的工作:

<%= search.input :cities, collection: City.all.order(name: :asc), as: :select, label: "City" %>

到此:

<%= search.select :cities, options_for_select(@cities) %>

但是,我还是想知道为什么其他方法不起作用?

1 个答案:

答案 0 :(得分:1)

<%= search.input :cities, collection: City.all.order(name: :asc), as: :select, label: "City" %>

上述代码无效的原因之一是

City.all.order(name: :asc)返回ActiveRecord::Relation个对象,但一个集合会搜索array or range.

集合可以是数组或范围。来自the collection documentation

该文件的另一点是,

当给出:collection时,:select输入将默认呈现,因此我们不需要传递as: :select

因此,将输入更改为

<%= search.input :cities, collection: City.uniq.pluck(:name).sort,label: "City" %>