6

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.

user984621
  • 46,344
  • 73
  • 224
  • 412
  • Not sure we have enough to go on. What is `go_to_action_path`? Is it a route? If so, what? If a method, we need the source. – Philip Hallstrom May 20 '18 at 15:29
  • That's an example of a path to a controller action (yes, it is a route). The above is a pseudocode. The question here is how to pass a `nil` value through a param and "receive" it on the other end in the controller action. – user984621 May 20 '18 at 15:32
  • Nimish's answer is probably the right one, but it would really help to see that controller action. Otherwise we can only guess. – Philip Hallstrom May 20 '18 at 15:43
  • Have you tried using `&` in your ERB? Simply put, it lets code work even if a param is `nil`. – Jake Jan 18 '19 at 23:49

1 Answers1

3

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
Nimish Gupta
  • 3,095
  • 1
  • 12
  • 20