Rails如何自动关联模型中的对象?

时间:2017-05-05 13:45:43

标签: ruby-on-rails ruby ruby-on-rails-3

我试图在创建订单对象时和创建pdata对象之后将订单obtecj与pdata对象关联起来。

但是在创建之后订单没有得到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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

应该是

unless data.nil
end

OR

if data.present?
end

答案 2 :(得分: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