开发者

comparing params in rails

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)


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜