как правильно создавать и обновлять посты с активными записями ассоциации? - PullRequest
0 голосов
/ 27 марта 2020

Итак, у меня возникла проблема: я не могу понять, как объявить контроллеры, чтобы они работали должным образом, у меня были разные ошибки, но моя главная проблема в том, что теперь я могу Не сохраняйте новый рецепт или не обновляйте «Tipo de Receita», который связан с моделью recipe_type, используемой в раскрывающемся списке, имейте в виду, что recipe_type.name будет заполнен заранее

, то есть edit.hmtl. эрб, который выполняет редактирование

<%= form_for @recipe do |f| %>
  <%= f.label :title, 'Título' %>
  <%= f.text_field :title %>
  <%= f.label :recipe_type, 'Tipo da Receita' %>
  <%= collection_select(:recipe, :recipe_type_id, RecipeType.all, :id, :name) %>
  <%= f.label :cuisine, 'Cozinha' %>
  <%= f.text_field :cuisine %>
  <%= f.label :difficulty, 'Dificuldade' %>
  <%= f.text_field :difficulty %>
  <%= f.label :cook_time, 'Tempo de Preparo' %>
  <%= f.number_field :cook_time %>
  <%= f.label :ingredients, 'Ingredientes' %>
  <%= f.text_area :ingredients %>
  <%= f.label :cook_method, 'Como Preparar' %>
  <%= f.text_area :cook_method %>
  <%= f.submit 'Enviar' %>
<% end %>

аналогично, это new.hmtl.erb, который регистрирует новые рецепты

<%= form_for @recipe do |f| %>
  <%= f.label :title, 'Título' %>
  <%= f.text_field :title %>
  <%= f.label :recipe_type, 'Tipo da Receita' %>
  <%= collection_select(:recipe, :recipe_type_id, RecipeType.all, :id, :name) %>
  <%= f.label :cuisine, 'Cozinha' %>
  <%= f.text_field :cuisine %>
  <%= f.label :difficulty, 'Dificuldade' %>
  <%= f.text_field :difficulty %>
  <%= f.label :cook_time, 'Tempo de Preparo' %>
  <%= f.number_field :cook_time %>
  <%= f.label :ingredients, 'Ingredientes' %>
  <%= f.text_area :ingredients %>
  <%= f.label :cook_method, 'Como Preparar' %>
  <%= f.text_area :cook_method %>
  <%= f.submit 'Enviar' %>
<% end %>

models / recipe_type, который используется в раскрывающемся меню

class RecipeType < ApplicationRecord
    has_many :recipes
    validates :name, presence: true
end

модели / рецепт, который получает модель recipe_type

class Recipe < ApplicationRecord
  belongs_to :recipe_type
  validates :title, :cuisine, :difficulty, :cook_time,
            :ingredients, :cook_method, presence: true

  def cook_time_min
    "#{cook_time} minutos"
  end
end

recipes.controller.rb

class RecipesController < ApplicationController
  def index
    @recipes = Recipe.all
  end

  def show
    @recipe = Recipe.find(params[:id])
  end

  def new
    @recipe = Recipe.new
    @recipe_type = RecipeType.all
  end

  def create
    @recipe_type = RecipeType.all
    @recipe = Recipe.new(recipe_params)
    if @recipe.save
      redirect_to @recipe
    else
      flash[:alert] = 'Você deve informar todos os dados da receita'
      render :new
    end
  end

  def edit
    @recipe_type = RecipeType.all
    @recipe = Recipe.find(params[:id])
    @recipe_type = RecipeType.all
  end

  def update
    @recipe = Recipe.find(params[:id])
    if @recipe.update(recipe_params)
      redirect_to @recipe
    else
      flash[:alert] = 'Você deve informar todos os dados da receita'
      render :edit
    end
  end

  private

  def recipe_params
    params.require(:recipe).permit(:title, :cuisine, :difficulty,
                                   :cook_time, :ingredients, :cook_method, :name)
  end

end

и это схема

ActiveRecord::Schema.define(version: 2020_03_26_013134) do

  create_table "recipe_types", force: :cascade do |t|
    t.string "name"
    t.integer "recipe_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["recipe_id"], name: "index_recipe_types_on_recipe_id"
  end

  create_table "recipes", force: :cascade do |t|
    t.string "title"
    t.string "cuisine"
    t.string "difficulty"
    t.integer "cook_time"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.text "ingredients"
    t.text "cook_method"
    t.integer "recipe_type_id"
    t.index ["recipe_type_id"], name: "index_recipes_on_recipe_type_id"
  end
end

Ответы [ 2 ]

2 голосов
/ 27 марта 2020

Одна проблема заключается в том, что вы не создаете входные данные из конструктора форм. Вы хотите использовать:

<%= f.label :recipe_type_id, 'Tipo da Receita' # key has to match input for accessibility %>
<%= f.collection_select(:recipe_type_id, RecipeType.all, :id, :name) %>

collection_select - вспомогательный помощник ввода, который просто создаст тег выбора, который не привязан к построителю форм и, следовательно, не к экземпляру вашей модели. Поэтому, если запись недействительна или вы обновляете существующую запись, ничего не будет выбрано.

f.collection_select - это метод в построителе форм, и он правильно установит значение recipe_type_id из экземпляра модели. завернутый в форму.

Вам также нужно разрешить параметр в вашем белом списке:

def recipe_params
  params.require(:recipe)
        .permit(
          :title, :cuisine, :difficulty,
          :cook_time, :ingredients, :cook_method, 
          :name, :recipe_type_id
        )
end
1 голос
/ 27 марта 2020

нужно добавить recipe_type_id в recipe_params:

def recipe_params
    params.require(:recipe).permit(:recipe_type_id ...)
end
...