Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 5 - in link_to, how to pass a nil (NULL) param?

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 0s instead of nils and then manually parse it in the controller action, but this is quite an ugly solution.

like image 209
user984621 Avatar asked May 20 '18 15:05

user984621


People also ask

Is nil and null the same in Ruby?

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.

What does nil mean in Ruby?

Well, nil is a special Ruby object used to represent an “empty” or “default” value.

How do you check if the value is null in rails?

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 .

How do I know if a class is nil Ruby?

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).


1 Answers

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
like image 134
Nimish Gupta Avatar answered Oct 02 '22 21:10

Nimish Gupta