在mackenziechild-recipe_box的第3周,我遇到了Cocoon的一些问题。我也有设计,以及当我创建一个新的Recipe
时,我的ingredients
和directions
属性不会被保存。但是当我更新现有的Recipe
时,一切都很好。该错误信息是:茧宝石属性创建新配方时不保存
主料配方必须存在,方向配方必须存在
我在做什么错?我使用的轨道5
应用程序/模型/ recipe.rb
class Recipe < ApplicationRecord
validates :title, :description, :image, presence: true
has_attached_file :image, styles: { medium: "400x400#" }
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
belongs_to :user
has_many :ingredients
has_many :directions
accepts_nested_attributes_for :ingredients, :reject_if => :all_blank, :allow_destroy => true
accepts_nested_attributes_for :directions, :reject_if => :all_blank, :allow_destroy => true
end
应用程序/控制器/ recipes_controller.rb
def new
@recipe = Recipe.new
@recipe = current_user.recipes.build
end
def create
@recipe = Recipe.new(recipe_params)
@recipe = current_user.recipes.build(recipe_params)
if @recipe.save
# show a success flash message and redirect to the recipe show page
flash[:success] = 'New recipe created successfully'
redirect_to @recipe
else
# show fail flash message and render to new page for another shot at creating a recipe
flash[:danger] = 'New recipe failed to save, try again'
render 'new'
end
end
def update
if @recipe.update(recipe_params)
# display a success flash and redirect to recipe show page
flash[:success] = 'Recipe updated successfully'
redirect_to @recipe
else
# display an alert flash and remain on edit page
flash[:danger] = 'Recipe failed to update, try again'
render 'edit'
end
end
private
def recipe_params
params.require(:recipe).permit(:title, :description, :image,
directions_attributes: [:id, :step, :_destroy],
ingredients_attributes: [:id, :name, :_destroy])
end
def recipe_link
@recipe = Recipe.find(params[:id])
end
应用程序/视图/配方/ _ingredient_fields。 html.haml部分
.form-inline.clearfix
.nested-fields
= f.input :name, input_html: { class: 'form-input form-control' }
= link_to_remove_association 'Remove', f, class: 'form-button btn btn-default'
应用程序/视图/配方/ _direction_fields.html.haml部分
.form-inline.clearfix
.nested-fields
= f.input :step, input_html: { class: 'form-input form-control' }
= link_to_remove_association 'Remove', f, class: 'form-button btn btn-default'
那一行,你得到这个错误?添加'inverse_of'实际上是否解决了任何问题(因为我从来没有这样做过)。在你的'create'中你创建了两次'@ recipe' - 你注意到了吗? – nathanvda