Rails: .require() without actually requiring it?
M

1

5

I'm trying to use...

params.require(:subscriber).permit(:utm_source, :utm_medium, :utm_campaign, :utm_term, :utm_content)

The problem is there are rare occasions where I want to do:

Subscriber.new(subscriber_params)

And I don't care if all the values are empty... When I do this it raises ActionController::ParameterMissing

So what I need is a way to make require() "optional" but still use it for the benefit of restricting nested parameters and for security, so people can't add in {admin: true} and things like that...

The actual params hash looks like:

{subscriber: {utm_source: 1, ...}

I can't change that part because it's used in many other places of the app. It's just this one spot.

Moloch answered 2/7, 2017 at 1:14 Comment(0)
K
9

You can use fetch instead of require:

params.fetch(:subscriber).permit(:utm_source, :utm_medium, :utm_campaign, :utm_term, :utm_content)

Check the rails guides for more information on strong parameters.

Kolomna answered 2/7, 2017 at 2:5 Comment(4)
Thanks! What is a 'scalar'? I read these docs and I didn't quite understand a few bitsMoloch
@Moloch A scalar could be described as a variable that holds a single value. For example, a number or a string are both scalar, but an array or hash are not. Check this post for a more detailed answer.Kolomna
if subscriber might be empty do it like: params.fetch(:subscriber, {}).permit(...)Semidome
params.fetch is not mentioned in that linkAshleyashli

© 2022 - 2024 — McMap. All rights reserved.