4

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.

Tallboy
  • 12,847
  • 13
  • 82
  • 173

1 Answers1

7

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.

Gerry
  • 10,337
  • 3
  • 31
  • 40
  • Thanks! What is a 'scalar'? I read these docs and I didn't quite understand a few bits – Tallboy Jul 02 '17 at 03:35
  • 2
    @Tallboy 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](https://softwareengineering.stackexchange.com/questions/238033/what-does-it-mean-when-data-is-scalar) for a more detailed answer. – Gerry Jul 02 '17 at 04:38
  • 2
    if subscriber might be empty do it like: params.fetch(:subscriber, {}).permit(...) – Pascal Aug 06 '20 at 15:12