我似乎无法弄清楚为什么Mongoid在创建新父项时不会为子对象设置嵌套属性。我想创建一个新的Folio,添加一个子功能,然后将其推送到Profile上的Folios数组。
我有一个配置文件,其中嵌入了许多Folios,它嵌入了许多功能:
class Profile
include Mongoid::Document
include Mongoid::Timestamps::Updated
#regular fields here; removed for brevity
embeds_many :folios, class_name: "Folio"
end
class Folio
include Mongoid::Document
include Mongoid::Timestamps::Updated
accepts_nested_attributes_for :features
embedded_in :profile
field :name
field :desc
field :order, type: Integer, default:0
embeds_many :features
attr_accessible :name, :desc, :order
end
class Feature
include Mongoid::Document
include Mongoid::Timestamps::Updated
embedded_in :folio
belongs_to :project
field :content_type, type: Integer #ContentType
field :content_id
field :txt, type: String
field :order, type: Integer, default:0
attr_accessible :project_id, :content_type, :content_id, :txt, :order
end
控制器:
def new
@folio = Folio.new
@folio.features.build
end
def create
@folio = Folio.new(params[:folio])
#@folio.features is still empty here.
@profile.folios << @folio
@profile.save
render "create_or_update.js"
end
在create中,param hash看起来不错:
{"folio"=>{"id"=>"new", "name"=>"new name", "desc"=>"new description", "features_attributes"=>{"0"=>{"project_id"=>"4ea0b68e291ebb44a100000a", "content_type"=>"1", "content_id"=>"4ea0b68e291ebb44a100000d", "txt"=>"note here"}}}, "commit"=>"Save", "action"=>"create", "controller"=>"folios"}
但是@ folio.features仍然是空的。
如果我记得,这对AR很好。奇怪的是,Folio上没有features_attributes =()方法。我认为嵌套属性需要工作吗?我错过了什么?
这是在带有Mongoid 2.2.3的Rails 3.1上。
答案 0 :(得分:0)
您是否尝试为Folio文档中的功能启用 AutoSave 为true
class Folio
include Mongoid::Document
include Mongoid::Timestamps::Updated
accepts_nested_attributes_for :features , :autosave => true
embedded_in :profile
end