2017-05-05 178 views
0

我试图在创建顺序对象和创建pdata对象之后将顺序obtecj与pdata对象关联。Rails如何自动关联模型中的对象?

,但创造的秩序并没有得到pdata_id

有人知道怎么做这个之后?

class Order < ActiveRecord::Base 

    belongs_to :product 
    belongs_to :pdata 

    after_create :create_pdata 

    def create_pdata 
    or_id = order.id 
    pr_id = product.id 

    data = Pdata.find_by_id(pr_id) 
    if data.nil? 
     attrs = product.attributes 
     attrs.delete('created_at') 
     attrs.delete('updated_at') 
     data = Pdata.create(attrs) 

     data = data.or_id 

     data.save 
    end 
    end 
end 

回答

0

应该

unless data.nil 
end 

OR

if data.present? 
end 
+0

谢谢@ MD-作为礼物送给-梅蒙我要检查它。 – bookaka

+0

以及显示: 的SQLite3 :: ConstraintException:UNIQUE约束失败:pdata.id:INSERT INTO – bookaka

+0

您需要删除'从ATTRS id' –

0

试着改变方法本

class Order < ActiveRecord::Base 

    belongs_to :product 
    belongs_to :pdata 

    after_create :create_pdata 

    def create_pdata 
    pdata = Pdata.find_by_id(product) 
    unless pdata 
     attrs = product.attributes.slice(:list, :of, :attributes. :you, :want) 
     pdata = Pdata.create(attrs) 
     self.pdata = pdata 
     self.save 
    end 
    end 
end 
+0

谢谢迪帕克,但我想哟与订单也联系起来,我可以用你的方法吗? – bookaka

+0

是'self.pdata = pdata'会将它与订单 –

+0

关联好吧,谢谢,以及我不知道为什么,但没有关联。 – bookaka

1
class Order < ActiveRecord::Base 

    belongs_to :product 
    belongs_to :pdata 

    # only initialize pdata when :pdata is not yet set (this can happen on `create` or on `update`). Change `before_save` to `before_create` if necessary. 
    before_save :initialize_pdata, unless: :pdata 

    def initialize_pdata 
    # initialize `pdata` with the attributes of the `product` record, only except `created_at`, `updated_at`, and `id`. Remove `id` below if you also want to copy the `id`. 
    # this method is called at `before_save`, so even if this is just initialised at the moment, when already "saving", this will also save/persist this initialised `pdata` object into the DB. 
    self.pdata = Pdata.new(
     product.attributes.except('created_at', 'updated_at', 'id') 
    ) 
    end 
end 
+0

谢谢Jay!非常好的方法! – bookaka

+0

@bookaka很高兴能有帮助:) –