#ruby-on-rails #ruby
#ruby-on-rails #ruby
Вопрос:
У меня есть модель элемента, как показано ниже.
class Item < ApplicationRecord
belongs_to :item_type, :class_name=>ItemType, :foreign_key=>"item_type_id"
end
и модель RecipeIngredient, как показано ниже
class RecipeIngredient < ApplicationRecord
belongs_to :item, :class_name=>Item, :foreign_key=>"item_id"
belongs_to :ingredient, :class_name=>Ingredient, :foreign_key=>"ingredient_id"
validates_numericality_of :quantity
end
Из индексного представления элементов я передаю item_id в индексное представление recipe_ingredients, как показано ниже
<td><%= link_to 'Add Recipe', recipe_ingredients_path(:item_id =>item.id) %></td>
и индексное представление recipe_ingredients отображает только те ингредиенты, которые принадлежат элементу с идентификатором item_id, полученному в URL. Для этого контроллер для RecipeIngredient выглядит следующим образом.
def index
@recipe_ingredients = RecipeIngredient.where(:item_id => params[:item_id])
end
теперь я пытаюсь передать тот же item_id в форму newrecipe ingredient со страницы индекса ингредиента рецепта следующим образом.
<%= link_to 'New Recipe Ingredient', new_recipe_ingredient_path(:item_id => @item_id) %>
и весь файл контроллера для ингредиентов рецепта, включая новые, приведен ниже.
class RecipeIngredientsController < ApplicationController
before_action :set_recipe_ingredient, only: [:show, :edit, :update, :destroy]
# GET /recipe_ingredients
# GET /recipe_ingredients.json
def index
@recipe_ingredients = RecipeIngredient.where(:item_id => params[:item_id])
end
# GET /recipe_ingredients/1
# GET /recipe_ingredients/1.json
def show
end
# GET /recipe_ingredients/new
def new
@recipe_ingredient = RecipeIngredient.new(:item_id => params[:item_id])
end
# GET /recipe_ingredients/1/edit
def edit
end
# POST /recipe_ingredients
# POST /recipe_ingredients.json
def create
@recipe_ingredient = RecipeIngredient.new(:item_id => params[:item_id])
respond_to do |format|
if @recipe_ingredient.save
format.html { redirect_to @recipe_ingredient, notice: 'Recipe ingredient was successfully created.' }
format.json { render :show, status: :created, location: @recipe_ingredient }
else
format.html { render :new }
format.json { render json: @recipe_ingredient.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /recipe_ingredients/1
# PATCH/PUT /recipe_ingredients/1.json
def update
respond_to do |format|
if @recipe_ingredient.update(recipe_ingredient_params)
format.html { redirect_to @recipe_ingredient, notice: 'Recipe ingredient was successfully updated.' }
format.json { render :show, status: :ok, location: @recipe_ingredient }
else
format.html { render :edit }
format.json { render json: @recipe_ingredient.errors, status: :unprocessable_entity }
end
end
end
# DELETE /recipe_ingredients/1
# DELETE /recipe_ingredients/1.json
def destroy
@recipe_ingredient.destroy
respond_to do |format|
format.html { redirect_to recipe_ingredients_url, notice: 'Recipe ingredient was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_recipe_ingredient
@recipe_ingredient = RecipeIngredient.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def recipe_ingredient_params
params.require(:recipe_ingredient).permit(:item_id, :ingredient_id, :quantity)
end
end
но URL-адрес нового ингредиента рецепта не содержит параметра, и, следовательно, приведенная ниже форма, в которой есть скрытое поле (обязательное) item_id, выдает ошибку, что поле пустое.
<%= form_for(recipe_ingredient) do |f| %>
<% if recipe_ingredient.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(recipe_ingredient.errors.count, "error") %> prohibited this recipe_ingredient from being saved:</h2>
<ul>
<% recipe_ingredient.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.hidden_field :item_id %>
</div>
<div class="field">
<%= f.label :ingredient_id %>
<%= f.collection_select :ingredient_id, Ingredient.all, :id, :ingredient %>
</div>
<div class="field">
<%= f.label :quantity %>
<%= f.text_field :quantity %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Ответ №1:
Вы не устанавливаете @item_id
переменную экземпляра, которую вы используете здесь:
<%= link_to 'New Recipe Ingredient', new_recipe_ingredient_path(:item_id => @item_id) %>
В действии контроллера для этого представления вы должны установить переменную:
@item_id = params[:item_id]
Или просто используйте параметры непосредственно в представлении:
<%= link_to 'New Recipe Ingredient', new_recipe_ingredient_path(item_id: params[:item_id]) %>
Комментарии:
1. Идеально! Теперь он передается в URL, но по-прежнему не сохраняется в скрытом поле item_id.
2. Понял. Пришлось изменить в контроллере с
3. Понял. Пришлось изменить в контроллере с
def create @recipe_ingredient = RecipeIngredient.new(:item_id => params[:item_id])
на@recipe_ingredient = RecipeIngredient.new(recipe_ingredient_params)