gpt4 book ai didi

ruby-on-rails - 如何使用 Rails 3 中的 Mongoid 嵌入资源创建嵌套表单?

转载 作者:行者123 更新时间:2023-12-02 05:20:23 26 4
gpt4 key购买 nike

我有一个食谱模型,其中嵌入了成分,使用 Mongoid。

class Recipe
include Mongoid::Document
include Mongoid::Timestamps

field :title, :type => String
embeds_many :ingredients

accepts_nested_attributes_for :ingredients, :reject_if => lambda { |a| a[:title].blank? }, :allow_destroy => true

validates :title, :presence => true
end

class Ingredient
include Mongoid::Document
field :name, :type => String
field :quantity, :type => String

embedded_in :recipe, :inverse_of => :ingredients
end

我希望能够同时创建一个新的食谱以及该食谱的相关成分,但我很难理解我将如何去做。这是我到目前为止所拥有的:

_form.html.erb - 在配方 View 中使用

<%= form_for @recipe do |f| %>  
...
<li>Title: <%= f.text_field :title %></li>

<% f.fields_for :ingredients do |builder| %>
<%= render "ingredient_fields", :f => builder %>
<% end %>
...
<%= f.submit %>

_ingredient_fields.html.erb

<%= f.text_field :name %>

配方 Controller

def new
@recipe = Recipe.new
@ingredient = @recipe.ingredients.build
end

def create
@recipe = Recipe.new(params[:recipe])


if @recipe.save
redirect_to @recipe, notice: 'Recipe was successfully created.'
else
render action: "new"
end
end

配料 Controller

def new
@recipe = Recipe.find(params[:recipe_id])
@ingredient = @recipe.ingredients.build
end

def create
@recipe = Recipe.find(params[:recipe_id])
@ingredient = @recipe.ingredients.build(params[:ingredient])
# if @recipe.save
end

这会呈现新的成分表单,但没有成分字段。谁能告诉我我做错了什么?

最佳答案

当您显示嵌套表单时,请尝试使用(注意等于):

<%= f.fields_for

而不仅仅是

<% f.fields_for

查看类似的question .

关于ruby-on-rails - 如何使用 Rails 3 中的 Mongoid 嵌入资源创建嵌套表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6685872/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com