-1

Im newbie on ruby on rails) Ok, I have controller with index action:

    def index
     condition = ['fulltime','parttime','remote','forone']. select{ |t|  params.has_key?(t.to_sym) }.join(' | ')
 Advert.search params[:search],:order => :created_at, :sort_mode => :desc,  :conditions => {:employment_type=>condition}

But it peace of code:

 ['fulltime','parttime','remote','forone']. select{ |t|  params.has_key?(t.to_sym) }

return nil

Why?:))

I don't want to write code with a bunch of checks like:

    if !fulltime.nil? && !fulltime.blank?
      condition = "fulltime"
    end


    if !parttime.nil? && !parttime.blank?
      if !condition.nil? && !condition.blank?
          condition = condition + " | parttime"
      else
        condition ="parttime"
      end

end

But my way with array.select method is not working:(

Could you give me some advices?) Thanks!

denisaaa08
  • 171
  • 1
  • 2
  • 11

1 Answers1

0

I tried your code on irb as follows:

> params = { :fulltime => "1" }
=> {:fulltime=>"1"}
> ['fulltime','parttime','remote','forone']. select{ |t|  params.has_key?(t.to_sym) }.join(' | ')
=> "fulltime"

So it is working fine. If you are getting nil from that code, then the params are being set to nil, or the params don't have any of ['fulltime','parttime','remote','forone'] as keys.

Check out Rails params explained? thread; likely to give an idea as to how to set the params correctly.

Community
  • 1
  • 1
Prakash Murthy
  • 12,923
  • 3
  • 46
  • 74