rails:从url中排除blank select_tag

时间:2012-08-21 13:22:05

标签: ruby-on-rails filter scope

我在index.html.erb上有一个表单(用户视图):

<%= form_tag( '', :method => :get ) do %>

<% @company = Position.all.map { |p| [ p.company, p.company ] } %>
<%= select_tag "company", options_for_select((@company), params[:position_id]), { :include_blank => true, :reject_if => @company.blank? } %> 

<% @industry = Position.all.map { |p| [ p.industry, p.industry ] } %>
<%= select_tag "industry", options_for_select((@industry), params[:position_id]), { :include_blank => true, :reject_if => @industry.blank? } %> 

<%= submit_tag 'Filter', class: 'btn btn-large btn-primary' %>
<% end %>

和控制器(用户控制器):

def index
    if params[:company] && params[:industry]
      @users = User.companies(params[:company]).industries(params[:industry])
    elsif params[:company]
      @users = User.companies(params[:company])
    elsif params[:industry]
      @users = User.companies(params[:industry])
    else 
      @users = User.all
    end
end

用户通过以下职位拥有许多公司和行业:

class User < ActiveRecord::Base
  attr_accessible :name, :email, :password, :password_confirmation, :first_name, :last_name, :position_ids

  has_many :positions
  has_many :companies, :through => :positions
  has_many :industries, :through => :positions
  has_one :current_position, :class_name => "Position", :conditions => { :is_current => true }

  scope :companies, lambda { |*company| {:include => :positions, :conditions => ["positions.company = ?", company]} }
  scope :industries, lambda { |*industry| {:include => :positions, :conditions => ["positions.industry = ?", industry]} }
end

尽管我的用户控制器中有if语句,但我无法忽略公司或行业领域中的空白条目。例如,空白公司和“Internet”行业过滤器返回此URL:

...用户UTF8 =%E2%9C%93&安培;公司=安培;行业=因特网&安培;提交=过滤

如何修改我的代码以忽略空白公司字段,以便网址排除'company =&amp;'完全?在这种情况下,我得到了我想要的返回结果:

...用户UTF8 =%E2%9C%93&安培;行业=因特网&安培;提交=过滤

谢谢!

1 个答案:

答案 0 :(得分:0)

您需要做的是检查参数是否为空白。

if !params[:company].blank? && !params[:industry].blank?
  @users = User.companies(params[:company]).industries(params[:industry])
elsif !params[:company].blank? && params[:industry].blank?
    @users = User.companies(params[:company])
elsif !params[:industry].blank? && params[:company].blank?
    @users = User.companies(params[:industry])
else
    @users = User.all
end

提交表单时,正在设置变量。就是这样,他们有空白的价值观。因此,您需要检查它们是否为空,而不是它们是否存在。