Search code examples
ruby-on-railsruby-on-rails-4nested-attributes

Include key/value pairs and single values in a hash


I have a nested attribute form which includes the fields:

  • nest[attr1][]
  • nest[attr2][]
  • nest[attr3]

(notice the third attribute is not an array)

In my controller, the strong params are as written:

params.require(:campaign).permit(
  :somevalue,
  nests_attributes: {
    attr1: [],
    attr2: [],
    :attr3
  }
)

This, of course, does not work because attr1 and attr2 are using key/value pairs to establish the array, while attr3 is a single value permitted.

How can I use both?


Solution

  • Given this params:

    {"campaign"=>{"somevalue"=>1, "nest"=>{"attr1"=>[1, 2, 3], "attr2"=>[1, 3, 4], "attr3"=>3}}}
    

    You can do this:

    params.require(:campaign).permit(
      :somevalue,
      nest: [:attr3, attr1: [], attr2: []]
    )
    

    You might find it weird to see [] with attr1: [] inside but it's totally valid syntax in Ruby. It will be interpreted as:

    [:attr3, {:attr1=>[], :attr2=>[]}]