In Rails 4 , the question is HOW to do this. I would like to know, although this works, WHY does the magazine still complain?
In Rails 5.1.3, I have a JSON ( letterhead) column as one of my model attributes (and inside that json is a hash with various attributes that I don't need for whitelisting). I just want to enable / whitelist a column.
Rails 5.1.4 Note
There is a Rails way to do this in 5.1.4, see this commit . There is a fairly lengthy discussion here about this. In Rails 5.1.4, this is simply the following:
def account_params
params.require(:account).permit(:id, :name, :plan_id, letterhead: {})
end
The parameter is :letterheadenabled, the error is not displayed in the log, and the model saves. But it is obvious that it allows arbitrary input inside this parameter, so use with caution.
If you want to limit which hash keys were allowed inside such a parameter, you can also whitelist, for example:
def account_params
params.require(:account).permit(:id, :name, :plan_id, letterhead: [:address, :logo, :contact_info])
end
Now this prevents any other arbitrary keys inside :letterhead, as I explicitly only allow these 3 -:address, :logo, :contact_info
Rails 5.1.3 (and earlier)
I can resolve this column using any of the following (see related discussion for other possible options):
Option 1
def account_params
params.require(:account).permit(:id, :name, :plan_id, :letterhead).tap do |whitelisted|
whitelisted[:letterhead] = params[:account].fetch(:letterhead, ActionController::Parameters.new).permit!
end
end
Option 2
def account_params
params.require(:account).permit(:id, :name, :plan_id, :letterhead).tap do |whitelisted|
whitelisted[:letterhead] = params[:account][:letterhead].permit!
end
end
In both cases, the model retains, but the journal still says “unlisted parameters: letterhead”
:
{"id"=>"a61151b8-deed-4efa-8cad-da1b143196c9",
"plan_id"=>"1dc49acf-3111-4030-aea1-7db259b53a51",
"name"=>"Test Account 1",
"is_active"=>true,
"letterhead"=>{"left"=>"", "center"=>"", "right"=>""},
"created_by"=>nil,
"updated_by"=>nil,
"created_at"=>"2017-10-14T19:05:40.197Z",
"updated_at"=>"2017-10-20T15:14:08.194Z"}