【问题标题】:Rails - create a record with nested attributeRails - 创建具有嵌套属性的记录
【发布时间】:2022-01-21 01:51:17
【问题描述】:

我收到格式如下的请求:

{
  recipe_translations: [{
      "lang": "en",
      "name": "wow",
      "value": "test"
    }]
}

Recipe:

class Recipe < ApplicationRecord
  has_many :recipe_translations, dependent: :destroy
  accepts_nested_attributes_for :recipe_translations
end

控制器:

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

显然,有些地方很不对劲,但不确定是什么。我得到的错误是:

#<ActiveRecord::AssociationTypeMismatch: RecipeTranslation(#69020) expected, got {\"lang\"=>\"en\", \"name\"=>\"wow\", \"value\"=>\"test\"} which is an instance of ActiveSupport::HashWithIndifferentAccess(#52480)>

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    接收到的参数应该是不同的格式,才能让 Rails 使用它。您可能希望根据 Rails 视图标准调整视图并使用它,而不是发布自定义的 (?) JSON 对象。

    【讨论】: