简体   繁体   English

Rails - 创建具有嵌套属性的记录

[英]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.

相关问题 在Rails中为嵌套属性添加空记录 - Adding empty record for nested attribute in rails 在 Rails 5 或 6 中为虚拟属性创建活动记录查询 - create active record query for virtual attribute in Rails 5 or 6 嵌套表单栏杆4保存创建时的现有记录 - nested form rails 4 save existing record on create 使用accepts_nested_attributes_for创建带有轨道的双嵌套记录 - Using accepts_nested_attributes_for to create a double nested record with rails 如何创建临时属性并在Rails活动记录中的json响应中使用它 - How to create temporary attribute & use that in json reponse in rails active record Rails-无法创建具有与该类同名的属性的记录 - Rails - Can't create a record that has an attribute with the same name of the class 如何在Rails中为Active Record更新方法创建动态属性 - How to create dynamic attribute in rails for Active Record update method 将属性设置为Rails记录 - Set an attribute to a Rails record 如果存在基于记录ID以外的属性的特定记录,Ruby on Rails如何创建新记录或更新? - How to create a new record or update if a particular record based on an attribute other than record id exists, Ruby on Rails? 使用通过关联和nested_form_for rails创建记录 - Create record using through association and nested_form_for rails
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM