Javascript variable in rails controller

I have a javascript variable on a form I need to check to perform an action (update) on the controller? Is my only option to add it to the params hash? or how can I check this value on the controller to make a decision?

Thx, Joe

If you want the server to use this variable as part of a request/response cycle, you’ll need to send that property to the server somehow. Since this is an update, you could add a parameter to the request that encodes that variable. It doesn’t have to be an attribute on the object, so you won’t need to add it to the strong params hash (you’re not using it to update the object, strictly speaking). But you may want to consider adding it to the model so all your validations can be in one place. Let’s say this is a “I agree to the terms and conditions”, but you don’t want or need to save that agreement in the model (kind of a stretch – I would actually want to save that along with the date they agreed).

class MyModel < ApplicationModel attribute :agreed, :boolean, default: false

validates :agreed, acceptance: true, on: :update end

(be sure to add :agreed to the array in your strong_params method)


<%= form.check_box :agreed %>

Now there’s no need to do anything out of the ordinary on the controller in the update method – if the checkbox isn’t checked, the form won’t update the model. The object won’t store this value, but it will be required on any update to be set to something truthy.

So if you want to fiddle that through JavaScript, just change the check_box to a hidden input, and let your JS modify it as necessary.


Thanks, I did add it to my strong params, it much easier to deal with.

I was using some jquery to hide the control (text field), but it didn’t hide the label :frowning: