0

I'm using the pgsearch gem and I'm having trouble allowing users to search by Gender what am I doing wrong? Firstly, when I click the gender drop down in search all I see is "1, 1, 1" horizontally.. When I should be seeing Male, Female.. I'm guessing this is because it is returning the user id's? Please see code below.

search_controller.rb

class SearchesController < ApplicationController
  before_filter :authenticate_user!

  def index
    if params[:search]
      @terms = params[:search][:terms] || nil
      @min_age = params[:search][:min_age] || nil
      @max_age = params[:search][:max_age] || nil
      @zipcode = params[:search][:zipcode] || nil
      @distance = params[:search][:distance] || nil
      @education_id = params[:search][:education_id] || nil
      @ethnicity_id = params[:search][:ethnicity_id] || nil
      @gender = params[:search][:gender] || nil
      @users = User.scoped_by_search(@terms, @min_age, @max_age, @education_id, @ethnicity_id, @gender)
    else
      @users = User.all
    end
  end
end

search#index.html.erb snippit

                   <div class="span12">
                    <label for="search[gender]">Gender:</label>
                    <%= select_tag 'education', options_from_collection_for_select(User.all, "id", "gender"), class: 'input-large', name: 'search[gender]', :prompt => "Select gender" %>

user.rb snippet relevant code

 def self.scoped_by_search(terms, min_age, max_age, education_id, ethnicity_id, gender)
    min = min_age.present? ? min_age : 18
    max = max_age.present? ? max_age : 100
    #TODO find a way to limit the number of users loaded - replace User.all below.
    users = terms.present? ? User.search(terms) : User.all
    users = users.where('age >= ? and age <= ?', min, max)
    users = users.where('education_id = ?', education_id) if education_id.present?
    users = users.where('ethnicity_id =?', ethnicity_id) if ethnicity_id.present?
    users = users.where('gender =?', gender) if gender.present?
    users
  end
end

GENDER = {
    0 => "Female",
    1 => "Male",
  }
Sonny Black
  • 1,585
  • 4
  • 23
  • 41

1 Answers1

0

This depends on how the Gender is being stored in User Model. If Female is being stored as 1 and Male is being stored as 0, then your drop down would only be showing those values.

The code snippet

GENDER = {
  0 => "Female",
  1 => "Male",
}

is not being used anywhere. If you want to use Male and Female throughout your application, storing them as such makes sense. For whatever reason, you need to store gender as 1 and 0, you can override the accessor in the User Model like

def gender
  case self.read_attribute(:gender)
    when '0'
      'Female'
    when '1'
      'Male'
    else
      nil
    end
  end
end
membLoper
  • 1,972
  • 19
  • 21