新手问题 mongoid 由 has_many 改为 polymorphic,应该要怎么做?

stephen · 2013年04月17日 · 最后由 stephen 回复于 2013年04月18日 · 2423 次阅读

原来的设计是 Product has_many Pictures 现在发现另外一个 Model 也 has_many Pictures。 所以我想设计为 polymorphic! 但是 product 本来已经有数据了,关联了一些图片。 现在代码改后,应该要怎么改变数据?

我写了几行代码

Product.all.each do |pr|
  pr.pictures.each do |p|
     p.update_attributes(:imageable_id => p.product.id, :imageable_type => p.product.class.name)
  end
end

但是好似执行了,数据还是为空的! 应该要怎么做?

好像是 p.update_attributes 不能保存!

在 update_attributes 下一行加上 Rails.logger.debug(p.errors) 看看是不是有错

或者换成 update_column 这个方法不会经过验证

@huacnlee

MOPED: 127.0.0.1:27017 QUERY        database=meiyuewuyou_development collection=pictures selector={"imageable_id"=>213, "imageable_type"=>"SanitaryTowel", "imageable_field"=>{"$in"=>[:pictures, nil]}} flags=[:slave_ok] limit=0 skip=0 fields=nil (0.4086ms)

其中一条,但是没返回错误! 情况是,执行了,但是没保存进数据库!

class Picture
  belongs_to :imageable, :polymorphic => true
end
class Deal
  has_many :pictures, :as => :imageable, :dependent => :destroy
end
class SanitaryTowel
  has_many :pictures, :as => :imageable, :dependent => :destroy
end

@sandy_xu 我的情况和他的不同!

Picture.all.each do |pic|
  if pic.product_id.present?
    pic.rename(:product_id, :imageable_id)
    pic.set(:imageable_type, 'Product')
  end
end

建议 Mongoid migration 中尽量用 set 等 Atomic http://mongoid.org/en/mongoid/docs/persistence.html#atomic

@HungYuHei 谢谢,用 atomic 可以解决!

需要 登录 后方可回复, 如果你还没有账号请 注册新账号