最近刚开始在实际项目中用 mongodb,遇到一些问题,请教一下大家。
class Policy
include Mongoid::Document
has_many :buckets
accepts_nested_attributes_for :buckets
field :min_device, :type => Integer, :default => 0
field :max_device, :type => Integer, :default => 10
field :name
end
class Bucket
include Mongoid::Document
belongs_to :policy
field :start_point, :type => Integer
field :end_point, :type => Integer
field :min, :type => Integer
field :max, :type => Integer
end
params = {"policy"=>{"name"=>"aaaaaa", "buckets_attributes"=>{"new_1326681393748"=>{"end_point"=>"4", "max"=>"4", "min"=>"1", "_destroy"=>"false", "start_point"=>"1"}, "0"=>{"end_point"=>"11", "max"=>"10", "min"=>"7", "_destroy"=>"false", "start_point"=>"9"}}, "min_device"=>"1", "max_device"=>"4"}}
步骤
@policy = Policy.new(params[:policy])
=> #<Policy _id: , name: "aaaaaa", min_device: 1, _type: nil, max_device: 4>
@policy.buckets
=> [#<Bucket _id: , policy_id: nil, end_point: 4, max: 4, _type: nil, min: 1, start_point: 1>, #<Bucket _id: , policy_id: nil, end_point: 11, max: 10, _type: nil, min: 7, start_point: 9>]
@policy.save
@policy
=> #<Policy _id: 10, name: "aaaaaa", min_device: 1, _type: nil, max_device: 4>
@policy.buckets
=> [#<Bucket _id: , policy_id: nil, end_point: 4, max: 4, _type: nil, min: 1, start_point: 1>, #<Bucket _id: , policy_id: nil, end_point: 11, max: 10, _type: nil, min: 7, start_point: 9>]
问题
搜了 stackoverflow 后 把 Policy 的 has_many :buckets 改成了 has_many :buckets, :autosave => true 后。重试以上步骤
@policy.buckets
=> [#<Bucket _id: 17, policy_id: nil, end_point: 4, max: 4, _type: nil, min: 1, start_point: 1>, #<Bucket _id: 18, policy_id: nil, end_point: 11, max: 10, _type: nil, min: 7, start_point: 9>]
bucket 保存了 id,但是 policy_id 仍然为空,他们的关联关系没有保存下来。为什么,有什么办法解决?
另外还有个小问题,embeds_many embeds_in 和 has_many belongs_to 区别在哪里?