I have a link where I need to pass a sequence of params, where 2 params are always nill.
link_to go_to_action_path(id, par_01, par_02, par_03, par_04)
In some cases are the par_01
and par_02
nil
, in other par_03
and par_04
.
If I have these values in the variables:
par_01 = nil
par_02 = nil
par_03 = 'a'
par_04 = 'b'
And then in the go_to_action
action:
p01 = params[:par_01]
p02 = params[:par_02]
p03 = params[:par_03]
p04 = params[:par_04]
I get these values:
p01 => a
p02 => b
p03 =>
p04 =>
In other words, the variables par_01
and par_02
will be thrown away and on their places will be moved in par_03
and par_04
.
How can I force the link_to
to accept a param with a nil
value? I was thinking about placing there 0
s instead of nil
s and then manually parse it in the controller action, but this is quite an ugly solution.
Let's start out with “Nil” since it's the most common and easy-to-understand way of representing nothingness in Ruby. In terms of what it means, Nil is exactly the same thing as null in other languages.
Well, nil is a special Ruby object used to represent an “empty” or “default” value.
You can check if an object is nil (null) by calling present? or blank? . @object. present? this will return false if the project is an empty string or nil .
In Ruby, you can check if an object is nil, just by calling the nil? on the object... even if the object is nil. That's quite logical if you think about it :) Side note : in Ruby, by convention, every method that ends with a question mark is designed to return a boolean (true or false).
You can pass hash
as the second option with id in your route
Use
link_to go_to_action_path(id, { par_01: par_01, par_02: par_02, par_03: par_03, par_04: par_04 })
Instead of
link_to go_to_action_path(id, par_01, par_02, par_03, par_04)
Then, In Controllers, say action name is action
# here you can use your params
def action
p01 = params[:par_01]
p02 = params[:par_02]
p03 = params[:par_03]
p04 = params[:par_04]
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With