加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何在Rails 3中使用Mongoid嵌入式资源创建嵌

发布时间:2020-12-17 01:18:32 所属栏目:百科 来源:网络整理
导读:我有一个食谱模型,其中嵌入了成分,使用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[:ti
我有一个食谱模型,其中嵌入了成分,使用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

这使得新成分形成,但成分没有领域.谁能给我任何关于我做错的指示?

解决方法

当您显示嵌套表单时,请尝试使用(注意等于):
<%= f.fields_for

而不仅仅是

<% f.fields_for

看到这个类似的question.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读