[英]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
: Recipe
:
class Recipe < ApplicationRecord
has_many :recipe_translations, dependent: :destroy
accepts_nested_attributes_for :recipe_translations
end
The controller: 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)>
The received parameers should be in a different format to be able to let Rails do something with it.接收到的参数应该采用不同的格式,以便让 Rails 能够对其进行处理。 You might want to adjust your view according to rails view standards and use this, rather then posting a customised (?) JSON object.
您可能想根据 Rails 视图标准调整视图并使用它,而不是发布自定义的 (?) JSON object。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.