【发布时间】:2020-03-31 19:02:36
【问题描述】:
我正在制作一个允许用户创建食谱的 Rails 应用程序。在新的食谱页面上,有食谱标题、作者等的输入字段,然后是成分的输入字段。创建新成分后,页面将重定向到“显示配方”页面。页面如何动态生成新的成分表,低于旧的成分表。
ingredients_controller.rb
class IngredientsController < ApplicationController
def create
@recipe = Recipe.find(params[:recipe_id])
@ingredient = @recipe.ingredients.create(ingredient_params)
redirect_to new_recipe_path(@recipe)
end
private
def ingredient_params
params.require(:ingredient).permit(:name, :amount, :uom)
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.ingredients.build
end
def edit
@recipe = Recipe.find(params[:id])
@recipe.ingredients.build
end
def create
@recipe = Recipe.new(recipe_params)
if @recipe.save
redirect_to @recipe
else
render 'new'
end
end
def update
@recipe = Recipe.find(params[:id])
if @recipe.update(recipe_params)
redirect_to @recipe
else
render 'edit'
end
end
def destroy
@recipe = Recipe.find(params[:id])
@recipe.destroy
redirect_to @recipe
end
private
def recipe_params
params.require(:recipe).permit(:title, :author, :note,
ingredients_attributes: [:id, :name, :amount, :uom])
end
end
我的表单被分成两部分,一份用于配方表单标题 _form.html.rb,另一份名为 _ingform.html.rb,_ingform.html.rb 在 _form.html.rb 和 _form.html.rb 中呈现在 new.html.rb 和 edit.html.rb 中呈现。
_form.html.rb
<link rel="stylesheet" type="text/css" href="app/assets/stylesheets/form.css">
<div id = "form">
<%= form_for(@recipe) do |form| %>
<% if @recipe.errors.any? %>
<div id = "error_explanation">
<h2>
<%= pluralize(@recipe.errors.count, "error") %>
prohibited this recipe from being saved:
</h2>
<ul>
<%@recipe.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= form.label :title %><br>
<%= form.text_field :title %>
</p>
<p>
<%= form.label :author %><br>
<%= form.text_field :author %>
</p>
<p>
<%= form.label :note %><br>
<%= form.text_area :note %>
</p>
<%= render 'ingform' %>
<p>
<%= form.submit %>
</p>
<% end %>
</div>
_ingform.html.rb
<link rel="stylesheet" type="text/css" href="app/assets/stylesheets/ingform.css">
<%= form_for(@recipe) do |form| %>
<h2>Add an Ingredient: </h2>
<%= form.fields_for :ingredients do |new| %>
<p class = "input_field">
<%= new.label :name, "name" %><br>
<%= new.text_field :name %>
</p>
<p class = "input_field">
<%= new.label :amount, "amount" %><br>
<%= new.number_field :amount %>
</p>
<p class = "input_field">
<%= new.label :uom, "UOM" %><br>
<%= new.text_field :uom %>
</p>
<p class = "input_field">
<%= new.submit %>
</p> </br>
<% end %>
<% end %>
配料属于食谱。 食谱.rb
class Recipe < ApplicationRecord
has_many :ingredients, :dependent => :delete_all
accepts_nested_attributes_for :ingredients, reject_if: :all_blank
validates :title, presence: true, length: {minimum: 4}
validates :author, presence: true
end
谢谢
【问题讨论】:
标签: html ruby-on-rails ruby