views:

112

answers:

2

I am doing

if params[:type] = "Type A"
   # do something
end
if params[:type] = "Type B"
   # do something
end

But I think that is wrong. I should be using ==

However that gives me error:

You have nil object when you didn't expect it

What is the best way to do this in rails?

All I am doing is getting a radio button variable from a form and doing logic based on its value (either Type A or Type B)

+4  A: 

Preamble

class Hash
  def try(arg)
    self[arg] rescue nil
  end
end

Your way

if params.try(:type) == "Type A"
    # do
elsif params.try(:type) == "Type B"
    # do
end

DRY

case params.try(:type)
when "Type A"
    # do
when "Type B"
    # do
else
    # default do
end
St.Woland
+1 for `#try`, I forgot about it
MBO
Object#try works on instances of ActiveRecord models because they all provide *methods* for each field in the row of the relation they represent. It does however not work on a hash as you have to use Hash#[]/Hash#fetch to access the hash content.
Caffeine
The solution does not throw an exception by the way because `params` does have the method `type`, which HashWithdifferentAccess/Hash inherited from Object: It is a deprecated alias for Object#class.See http://ruby-doc.org/core/classes/Object.html#M000349
Caffeine
You may define `try` as shown.
St.Woland
+3  A: 

You're sure it should be params[:type]? First, check your logs to see what is inside params before you access action in controller.

To check multiple choices you can use switch construct:

case params[:type]
when "Type A"
  # do sth
when "Type B"
  # do sth
else # not A nor B, can be nil
  # do nothing
end

And if you need to deeper inside params then you can use if/else:

if params[:type] && params[:type][:value] == "sth"
  # do sth
elsif params[:type] && params[:type][:value] == "..."
  # do sth
end

And check where you get your error from, because in Ruby you can easily compare nil and String, so it's not because of using == in your example.

MBO