'Rails - create a record with nested attribute
I'm receiving a request in the format:
{
recipe_translations: [{
"lang": "en",
"name": "wow",
"value": "test"
}]
}
The Recipe:
class Recipe < ApplicationRecord
has_many :recipe_translations, dependent: :destroy
accepts_nested_attributes_for :recipe_translations
end
The controller:
class RecipesController < ApplicationController
def create
recipe = Recipe.new(recipe_params)
end
def recipe_params
# whitelist params
params.permit(recipe_translations: %i[lang name value])
end
end
Obviously, something is very wrong but not sure what. The error I'm getting is:
#<ActiveRecord::AssociationTypeMismatch: RecipeTranslation(#69020) expected, got {\"lang\"=>\"en\", \"name\"=>\"wow\", \"value\"=>\"test\"} which is an instance of ActiveSupport::HashWithIndifferentAccess(#52480)>
Solution 1:[1]
You can use:
def recipe_params
params.fetch(:recipe_translations, {}).permit(%w[lang name value])
end
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | double_u1 |
