如何在ActiveRecord模型中创建默认关联?

时间:2012-06-24 16:05:57

标签: ruby-on-rails ruby activerecord ruby-on-rails-3.2

在Rails 3.2中,我尝试在创建OdontologicUnity时设置默认User实例。

用户:

require "odontological_unity"
class User < ActiveRecord::Base

    attr_accessible :odontologic_unity, ...
    ...

    belongs_to :odontologic_unity

    after_create :associate_default_unity

    private 
    def associate_default_unity
      ou = OdontologicUnity::DEFAULT
      ou.save!
      self.update_attribute :odontologic_unity, ou
    end

end

OdontologicUnity:

# encoding: UTF-8
class OdontologicUnity < ActiveRecord::Base
  ...

  DEFAULT = OdontologicUnity.new(
    name: 'Actualiza el nombre',
    address: 'Actualiza la dirección',
    nit: 'Actualiza el NIT',
    mission: "Actualiza la misión",
    vision: "Actualiza la visión"
  )
end

代码可以在不引发异常的情况下工作,但是当我看到我的数据库时,我得到了这个(odontological_unity_id: nil):

User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 9]] => #<User id: 9, email: "user2@example.com", password_digest: "$2a$10$BPDmM6stW0sO6tQbwwJCxuWO4hvWIAeSzogEl2GGiqmo...", remember_token: "ltU5RBcifDsr9uPIci9z_A", names: "Example User", lastnames: "Some Lastnames", identity_document_number: "1515", odontological_unity_id: nil, created_at: "2012-06-24 15:00:17", updated_at: "2012-06-24 15:02:05">

关于它的奇怪之处在于OdontologicUnity记录实际上已创建,但并未与用户关联。

1 个答案:

答案 0 :(得分:3)

我建议您使用一种方法来创建默认用户,而不是常量。关于你的问题,请在创建之前尝试a并分配id:

before_create :associate_default_unity

def associate_default_unity
  ou = OdontologicUnity::DEFAULT
  ou.save!
  self.write_attribute :odontologic_unity_id, ou.id
end