cocoon gem 属性在创建新配方时未保存

cocoon gem attributes not saving when creating new recipe

在 mackenziechild-recipe_box 的第 3 周,我遇到了 Cocoon 的一些问题。我也安装了设计,但是当我创建一个新的 Recipe 时,我的 ingredientsdirections 属性没有被保存。但是当我更新现有的 Recipe 时,一切都很好。错误信息是:

Ingredients recipe must exist, directions recipe must exist

我做错了什么?我正在使用 rails 5

app/models/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

app/controllers/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

app/views/recipes/_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'

app/views/recipes/_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'

But when I update an existing Recipe, everything is fine.

这就是你的答案。当您创建新配方时,您没有配方对象,因为它在服务器内存中。但是当你更新它时,配方对象会被保留。

这就是您收到 Ingredients recipe must existdirections recipe must exist 错误的原因。

要解决这个问题,您必须在关联中添加 inverse_of

class Recipe
  has_many :ingredients, inverse_of: :recipe
  has_many :directions, inverse_of: :recipe

class Ingredient
  belongs_to :recipe, inverse_of: :ingredients

class Direction
  belongs_to :recipe, inverse_of: :directions

当您包含 inverse_of 时,Rails 现在知道这些关联并将 "match" 它们存储在内存中。

关于inverse_of的更多信息: