Mongoid嵌入式模型不写?

时间:2016-04-03 15:43:10

标签: ruby-on-rails mongoid

我尝试过很多不同问题的解决方案。 当我创建一个新的配方并为其嵌入式模型赋予它属性时,会发现它没有保存它们。

型号:

class Recipe
 include Mongoid::Document
 include Mongoid::Timestamps
 field :title, type: String
 ...

 embeds_many :ilists
 accepts_nested_attributes_for :ilists,
 :allow_destroy => true,
 :reject_if     => :all_blank,
 :autosave => true
end

class Ilist
 include Mongoid::Document
 field :name, type: String
 field :quantity, type: Integer

 embedded_in :recipe, inverse_of: :ilists
end

控制器:

class RecipesController < ApplicationController
 before_action :set_recipe, only: [:show, :edit, :update, :destroy]
def new
 @recipe = Recipe.new
 @recipe.ilists.build
end
def create
@recipe = Recipe.new(recipe_params)
respond_to do |format|
  if @recipe.save
    format.html { redirect_to @recipe, notice: 'Recipe was successfully created.' }
    format.json { render :show, status: :created, location: @recipe }
  else
    format.html { render :new }
    format.json { render json: @recipe.errors, status: :unprocessable_entity }
  end
end
...
end

class IlistController < ApplicationController
def new
    @ilist = @recipe.ilist.build
 end
end

形式:

<%= form_for(@recipe) do |f| %>
...
<%= f.fields_for :ilists do |builder| %>

    <tr>
    <td><%= builder.text_field :name %></td>
    <td><%= builder.text_field :quantity %></td>
    <td><%= builder.check_box :_destroy %><%= builder.label :_destroy, "Remove Ingrediant" %></td>
    </tr>

<% end %>
...
<div class="actions">
<%= f.submit %></div>
<% end %>

一旦我点击提交所有内容,但保存了嵌入的文档属性。使用控制台并给一些食谱配给一些“黑客”#39;表明我正确地渲染它们,并且当我点击编辑每个字段时显示正确的值,它们只是不保存。这是一个大学项目,非常感谢帮助。

0 个答案:

没有答案