0

我有以下内容:

class Publication < ActiveRecord::Base
  belongs_to :project, :inverse_of => :publication

  before_create :bind_project

  private
    def bind_project
      self.create_project
    end
end

class Project < ActiveRecord::Base
  has_one :publication, :inverse_of => :project
end

据此,在创建新模型Publication时,模型上的publication_id属性project应由create_project方法设置。

为什么它没有发生?

这就是我看到的bind_project

  • self.project_id设置正确
  • self.project.publication_idNULL
  • self.project.publication.id设置正确

数据库也反映了这一点:projects.publication_id列是NULL.

4

1 回答 1

1

似乎有点奇怪,您尝试在回调中访问该create_project方法。before_create错字?after_create回调似乎更合适。

此外:您需要关联方面的publication_id属性做什么?has_one侧面只需要一个_id属性belongs_to

我的第一段的附录:正如我所看到的,您正在尝试create_project在实际基础对象创建完成之前对关联对象(方法)使用 Rails 魔法。尽管这可能有效,但这将是我要调查的第一点。

于 2012-09-20T19:19:31.250 回答