希望有人可以在这里提出修复建议。我对 Rails 还很陌生,正在探索 Rails 4.0 中的变化。我在 Rails 4.0 中构建了这个简单的食谱书应用程序。我有一个主要的食谱模型(名称、cook_time、oven_temp、说明等)。因为有些食谱可能有 5 种成分,而另一些可能有 20 种成分,所以我想用 has_many 关联在单独的模型中分解成分。因此,Recipes has_many Ingredients 和 accept_nested_attributes_for :ingredients。以下是模型:
食谱.rb
class Recipe < ActiveRecord::Base
belongs_to :user
belongs_to :category
has_many :ingredients, :dependent => :destroy
validates :name, presence: true, length: { maximum: 50 }
accepts_nested_attributes_for :ingredients,
:reject_if => lambda { |a| a[:name].blank? },
:allow_destroy => true
end
成分.rb
class Ingredient < ActiveRecord::Base
belongs_to :recipe
end
提醒:Rails 4.0 不再使用 attr_accessible,而是将赋值转移到具有强参数的控制器中。
recipes_controller.rb
class RecipesController < ApplicationController
before_action :find_recipe, only: [:show, :edit, :update, :destroy]
before_action :set_current_user, except: [:index, :show]
respond_to :html, :js
...
def edit
end
def update
if @recipe.update_attributes(recipe_params)
redirect_to @recipe
else
render :edit
end
end
...
def find_recipe
@recipe = Recipe.find(params[:id])
end
private
def recipe_params
params.require(:recipe).permit( :id, :name, :category_id, :cook_time, :oven_temp, :calories, :instructions, :notes, :email, ingredients_attributes: [:id, :name])
end
end
我正在使用来自 nathanvda 的优秀 Cocoon gem 来动态管理嵌套表单字段,它在“recipes#new”中效果很好,并且可以正确保存信息。但是,成分字段不会出现在“recipes#edit”视图中!这是我的“表单”和成分字段部分的代码。
_form.html.erb(缩写)
<%= form_for @recipe, html: { class: 'form-horizontal' } do |f| %>
<fieldset>
<legend>Main Information</legend>
<div class="field form-group">
<%= f.label :name, "Recipe name", class: "col-lg-2 control-label" %>
<div class="col-lg-5">
<%= f.text_field :name, class: "form-control" %>
</div>
</div>
<div class="field form-group">
<%= f.label :cook_time, class: "col-lg-2 control-label" %>
<div class="col-lg-5">
<%= f.text_field :cook_time, class: "form-control" %>
</div>
</div>
...
</fieldset>
<legend>Ingredients</legend>
<p>Number of ingredients: <%= f.object.ingredients.count unless f.object.ingredients.nil? %></p>
<fieldset id="ingredients">
<% f.fields_for :ingredients do |builder| %>
<%= render 'ingredient_fields', :f => builder %>
<% end %>
<p class="links">
<%= link_to_add_association 'add ingredient', f, :ingredients, { class:"btn btn-primary" } %>
</p>
</fieldset>
<fieldset>
<legend>How to make it</legend>
<div class="field form-group">
<%= f.label :instructions, class: "col-lg-2 control-label" %>
<div class="col-lg-5">
<%= f.text_area :instructions, class: "form-control", rows: "7" %>
</div>
</div>
...
</div>
</fieldset>
<% end %>
_ingredients_fields.html.erb
<div class="nested-fields">
<div class="form-group">
<%= f.label :name, "Ingredient", class: "col-lg-2 control-label" %>
<div class="col-lg-5">
<%= f.text_field :name, class: "form-control" %>
</div>
<%= link_to_remove_association "remove", f %>
</div>
</div>
正如我所说,非常简单,删除了所有错误检查和消息传递,只是基础。关于我所缺少的任何想法?当我从显示视图加载编辑时,我知道食谱中有成分。提前感谢您的任何建议!
凯文