【问题标题】:How do I create a nested form using Mongoid embedded resources in Rails 3?如何使用 Rails 3 中的 Mongoid 嵌入式资源创建嵌套表单?
【发布时间】:2011-07-13 21:24:31
【问题描述】:

我有一个配方模型,其中嵌入了成分,使用 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 - 用于配方视图

<%= 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 %>

配方控制器

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

配料控制器

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

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

【问题讨论】:

  • 如果我缺少解决此问题所需的任何信息,请告诉我,因为我仍然对这个问题感到困惑......

标签: ruby-on-rails ruby-on-rails-3 mongodb mongoid ruby-on-rails-3.1


【解决方案1】:

当你显示嵌套表单时,尝试使用(注意等号):

<%= f.fields_for

不仅仅是

<% f.fields_for

看到这个类似的question

【讨论】:

    【解决方案2】:

    我最近遇到了一个非常相似的问题。我发现在 Github 上的 Mongoid 问题跟踪器上发布的类似问题非常有帮助:

    https://github.com/mongoid/mongoid/issues/1468#issuecomment-6898898

    瘦的是那条线

    = f.fields_for :ingredients do |builder|
    

    应该是这样的:

    = f.fields_for @recipe.ingredients do |builder|
    

    【讨论】:

    • 也许您遇到了其他问题?
    猜你喜欢
    • 2011-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多