【发布时间】:2017-01-09 02:54:07
【问题描述】:
我正在尝试保存一个包含配方和多种成分的对象。数据来自我的 angular 2 应用程序,它将对象作为 JSON 传递。我的 rails 5 api 应用程序将接收配方对象并使用强参数将其直接保存到我的数据库中。现在我可以将配方对象保存到数据库中,但由于某种原因,其中的成分没有被保存。我检查了 rails 文档,发现我当前的代码没有问题。任何想法将不胜感激。
食谱.rb
class Recipe < ApplicationRecord
has_many :ingredients
accepts_nested_attributes_for :ingredients
end
成分.rb
class Ingredient < ApplicationRecord
belongs_to :recipe
end
recipe_controller.rb
def create
@recipe = Recipe.new(recipe_params)
if @recipe.save
render json: @recipe, status: :created, location: @recipe
else
render json: @recipe.errors, status: :unprocessable_entity
end
end
def recipe_params
params.require(:recipe).permit(:name , :description, :imagePath, ingredients_attributes: [ :id, :name, :amount])
end
我的控制台日志
Started POST "/recipes" for ::1 at 2017-01-09 11:40:44 +0900
ActiveRecord::SchemaMigrationLoad(0.3ms)SELECT`schema_migrations`.* FROM `schema_migrations`
Processing by RecipesController#create as HTML Parameters: {"name"=>"Spaghetti", "imagePath"=>"http://cdn2.tmbi.com/TOH/Images/Photos/37/300x300/exps36749_SD143203D10__25_1b.jpg", "description"=>"Delicious spaghetti", "ingredients"=>[{"name"=>"Tomato", "amount"=>1}, {"name"=>"Pasta", "amount"=>1}], "recipe"=>{"name"=>"Spaghetti", "description"=>"Delicious spaghetti", "imagePath"=>"http://cdn2.tmbi.com/TOH/Images/Photos/37/300x300/exps36749_SD143203D10__25_1b.jpg"}}
(0.1ms) BEGIN
SQL (0.2ms) INSERT INTO `recipes` (`name`, `description`, `imagePath`, `created_at`, `updated_at`) VALUES ('Spaghetti', 'Delicious spaghetti', 'http://cdn2.tmbi.com/TOH/Images/Photos/37/300x300/exps36749_SD143203D10__25_1b.jpg', '2017-01-09 02:40:44', '2017-01-09 02:40:44')
(0.7ms) COMMIT
Completed 201 Created in 9ms (Views: 1.0ms | ActiveRecord: 2.1ms)
【问题讨论】:
-
不是强参数吗?这是好帖子how to permit array in strong params
-
我已经试过了,它只是忽略了配方对象中的成分。
标签: ruby-on-rails angularjs activerecord ruby-on-rails-5 strong-parameters