Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strong parameters permit all attributes for nested attributes

Is there a way in strong parameters to permit all attributes of a nested_attributes model? Here is a sample code.

class Lever < ActiveRecord::Base  has_one :lever_benefit  accepts_nested_attributes_for :lever_benefit end  class LeverBenefit < ActiveRecord::Base   # == Schema Information   #  id          :integer          not null, primary key   #  lever_id    :integer   #  explanation :text end 

For lever strong parameters i am writing currently this

def lever  params.require(:lever).permit(:name,:lever_benefit_attributes => [:lever_id, :explanation]) end 

Is there a way for nested attributes i can write to permit all attributes without explicitly giving the attributes name like lever_id and explanation ?

Note: Please don't get confused with this question with permit! or permit(:all) this is for permitting all for nested attributes

like image 614
AnkitG Avatar asked Jul 23 '13 12:07

AnkitG


People also ask

What are nested attributes?

Nested attributes provide a mechanism for updating documents and their associations in a single operation by nesting attributes in a single parameters hash. This is useful when wanting to edit multiple documents within a single web form.

What are strong parameters?

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.


2 Answers

The only situation I have encountered where permitting arbitrary keys in a nested params hash seems reasonable to me is when writing to a serialized column. I've managed to handle it like this:

class Post   serialize :options, JSON end  class PostsController < ApplicationController   ...    def post_params     all_options = params.require(:post)[:options].try(:permit!)     params.require(:post).permit(:title).merge(:options => all_options)   end end 

try makes sure we do not require the presents of an :options key.

like image 138
tfischbach Avatar answered Oct 05 '22 10:10

tfischbach


Actually there is a way to just white-list all nested parameters.

params.require(:lever).permit(:name).tap do |whitelisted|   whitelisted[:lever_benefit_attributes ] = params[:lever][:lever_benefit_attributes ] end 

This method has advantage over other solutions. It allows to permit deep-nested parameters.

While other solutions like:

nested_keys = params.require(:lever).fetch(:lever_benefit_attributes, {}).keys params.require(:lever).permit(:name,:lever_benefit_attributes => nested_keys) 

Don't.


Source:

https://github.com/rails/rails/issues/9454#issuecomment-14167664

like image 29
nothing-special-here Avatar answered Oct 05 '22 09:10

nothing-special-here