0

J'essaie de créer une forme imbriquée qui va combiner 2 attributs pour deux modèles associés. Disons que j'ai 3 modèles: Recette (modèle principal), RecipeIngredient (modèle de joint pour la recette et les ingrédients) et Ingrédient.Imbrication de plusieurs modèles avec cocon

code est ci-dessous:

class Recipe < ApplicationRecord 
    has_many :directions, inverse_of: :recipe 
    has_many :recipe_ingredients, inverse_of: :recipe 
    has_many :ingredients, through: :recipe_ingredients 

    accepts_nested_attributes_for :ingredients, 
            reject_if: proc { |attributes| attributes['name'].blank? }, 
            allow_destroy: true 
    accepts_nested_attributes_for :directions, 
            reject_if: proc { |attributes| attributes['step'].blank? }, 
            allow_destroy: true 
    accepts_nested_attributes_for :recipe_ingredients, 
            reject_if: proc { |attributes| attributes['quantity'].blank? }, 
            allow_destroy: true 


    validates :tittle, :description, :image, presence: true 
    has_attached_file :image, styles: { :medium => "400x400#" } 
    validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/ 

end 
class Ingredient < ApplicationRecord 
    has_many :recipe_ingredient, inverse_of: :ingredient 
    has_many :recipes, through: :recipe_ingredient 
end 
class RecipeIngredient < ApplicationRecord 
    belongs_to :recipe 
    belongs_to :ingredient, inverse_of: :recipe_ingredient 

end 

Mon imbrication:

.col-md-6 
       %h3 Skladniki 
       #ingredients 
        = f.simple_fields_for :recipe_ingredients do |recipe_ingredient| 
         =render 'recipe_ingredient_fields', f: recipe_ingredient 
        .links 
         = link_to_add_association 'Dodaj skladnik', f, :recipe_ingredients, class: "btn btn-default add-button", :wrap_object => Proc.new {|recipe_ingredient| recipe_ingredient.build_ingredient; recipe_ingredient } 

Ici vous pouvez voir que je vois essaie d'accéder à deux attributs: 1. quantité (de RecipeIngredient de classe) - cette partie est ok 2. nom (de la classe des ingrédients) - cette partie est KO completly

.form-inline.clearfix 
     .nested-fields 
      = f.input :quantity, :label => "Ilość", input_html: { class: "form-input form-control" } 
      = f.fields_for :ingredients_attributes do |ingr| 
       = ingr.input :name, :label => "Nazwa", input_html: { class: "form-input form-control" } 

      = link_to_remove_association "Usun", f, class: "form-button btn btn-default" 

Lors de la validation, je reçois cette erreur

ingrédient des Ingrédients de la recette doit exister

Et voici pourquoi:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"nw14a3HkgSrjE+QpIK4POEzTOqBhtE/EMe+CarWkmI6CSRf0GAdWZGzJQRD4aPurNDNm96TJbt60mc1hl+1JPA==", "recipe"=>{"tittle"=>"Tosty", "description"=>"Testowy przepis", "preparation_time"=>"10.0", "portion"=>"2", "recipe_ingredients_attributes"=>{"1507996685991"=>{"quantity"=>"432", "ingredients_attributes"=>{"name"=>"fasdd"}, "_destroy"=>"false"}, "1507996689888"=>{"quantity"=>"2134432342", "ingredients_attributes"=>{"name"=>"dsad"}, "_destroy"=>"false"}}, "directions_attributes"=>{"0"=>{"step"=>"Krok1", "_destroy"=>"false", "id"=>"1"}, "1"=>{"step"=>"Krok2", "_destroy"=>"false", "id"=>"2"}}}, "commit"=>"Update Recipe", "id"=>"5"} 
    Recipe Load (0.3ms) SELECT "recipes".* FROM "recipes" WHERE "recipes"."id" = ? LIMIT ? [["id", 5], ["LIMIT", 1]] 
Unpermitted parameter: ingredients_attributes 
Unpermitted parameter: ingredients_attributes 
    (0.2ms) begin transaction 
    Direction Load (0.3ms) SELECT "directions".* FROM "directions" WHERE "directions"."recipe_id" = ? AND "directions"."id" IN (1, 2) [["recipe_id", 5]] 
    (0.2ms) rollback transaction 

arguments passés à la méthode juste ne pas la définition de correspondance de recipe_params (méthode privée en recipe_controller):

def recipe_params 
     params.require(:recipe).permit(:tittle, :description, :image, :portion, :preparation_time, ingredients_attributes: [:id, :name, :_destroy], directions_attributes: [:id, :step, :_destroy], recipe_ingredients_attributes: [:id, :quantity, :_destroy]) 
    end 

Le point est ... comment le réparer? Alors les ingredients_attributes seront passés de recipe_ingredients_attributes?

Répondre

1

L'erreur dans le fichier journal indique que le paramètre ingredients_attributes n'est pas autorisé. Si vous vérifiez les paramètres passés, vous pouvez voir que le recipe_ingredients_attributes contient le ingredients_attributes et cela n'est pas autorisé par votre définition de paramètres forts (la méthode recipe_params): il doit également prendre en charge l'imbrication correcte.

+0

Je sais où est le problème. Le fait est que je ne sais pas comment résoudre ce problème. Avant d'utiliser un formulaire imbriqué avec l'attribut de quantité inclus dans le modèle d'ingrédient. Mais pour la fonctionnalité, j'ai dû ajouter le modèle de jointure et maintenant je ne sais pas comment générer correctement les contrôles associes pour Ingredient: name et RecipeIngredient: quantité – MajQel