Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails strong parameter not accepting array of hashes

I have a group controller which accepts array of hashes as parameter for POST request for create action

  def create
    response = Group.create(current_user_id, group_params)
    render json: response
  end

  def group_params
    params.require(:group).permit(:group_name, :group_title, group_members: [])
  end

But its not accepting the group_members parameter via strong parameter

Here is what the incoming request with params looks like in my app

Started POST "/groups" for 127.0.0.1 at 2014-08-04 08:25:37 +0545
Processing by GroupsController#create as JSON
  Parameters: {"group"=>{"group_name"=>"Fourth group", "group_title"=>"fourth tester", "group_members"=>[{"id"=>"0833be3c-17db-11e4-904b-3f662703cb5b", "darknet_accountname"=>"@ckgagan", "access_level"=>"Write"}]}}
Unpermitted parameters: group_members
Completed 200 OK in 10ms (Views: 0.2ms)

I have seen many posts which says that adding group_members : [] inside permit will work but its not working in my case.

like image 727
Gagan Avatar asked Aug 04 '14 03:08

Gagan


People also ask

Do strong params permit nested arrays last?

TLDR: Strong Params must permit nested arrays last! Strong Parameters, aka Strong Params, are used in many Rails applications to increase the security of data sent through forms. Strong Params allow developers to specify in the controller which parameters are accepted and used.

Should you use strong parameters in your Ruby on Rails application?

Additionally, if the Ruby on Rails application in question was an API, Strong Parameters would only be effective in very specific circumstances. Since the feedback given by Strong Parameters is not as granular as an API would like to be, it could be hard to find many uses of it.

Should strong parameters be nested or not?

This issue with Strong Parameters is very specific and can often be avoided by redefining how data is organized and avoiding nested arrays. However, for times when nested Strong Params seems to be the best solution, it is important to remember that nested parameters will be ignored within the Strong Parameters unless they are permitted last.

What are the reasons not to use strong params?

The first is out due to data security. Strong params exist fro a reason and to stray from them seems unwise since they protect against any data breaches in the code by limiting the information a user can pass in. The second is out because it just seems too unwieldy and repetitive.


1 Answers

Solved the problem by adding the group_members field inside permit args.

def group_params
   params.require(:group).permit(:group_name, :group_title, group_members: [:id, :darknet_accountname, :access_level])
end

After this there was no complaint about unpermitted parameters within group_members.

like image 168
Gagan Avatar answered Sep 21 '22 16:09

Gagan