Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Permitting array of hashes rails 5

My rails version is 5 and I have request param like this,

{ "segment": {
    "name": "test",
    "new_filters": [
      {"criteria": "sad",
        "other_keys": [{"key": "value"}]
      }, 
      {"criteria": "sad",
        "other_keys1": [{"key1": "value1"}]
      }]
}
}

I am stuck in permitting the new_filter params in rails controller, I am trying below code,

params.require(:segment).permit(:name, :people_count, new_filters: [])

and still getting the error. But this is not the case while having array of strings in new_filter key. Eg: ["sad", "asdasd"]. How to get the nested structure as whitelisted attribute?

like image 407
Aarthi Avatar asked Dec 15 '25 05:12

Aarthi


2 Answers

This worked for me when testing with your attributes:

params.require(:segment).permit(:name, :people_count, new_filters: [:criteria, other_keys: [:key], other_keys1: [:key1]])
like image 54
James Burke Avatar answered Dec 16 '25 17:12

James Burke


In your model file for segment try adding the line

accepts_nested_attributes_for :new_filters

this should allow you to pass those attributes.

https://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

like image 44
Corey Gibson Avatar answered Dec 16 '25 19:12

Corey Gibson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!