Rails belongs_to has_many关系,主应用和引擎

时间:2015-10-19 16:37:20

标签: ruby-on-rails-4 activerecord foreign-key-relationship rails-models monologue

我正在使用名为Monologue的rails博客引擎。我希望其中一个引擎的模型与我的主应用程序模型有一个belongs_to和has_many关系。用户(作者)可以有许多帖子,帖子属于作者(用户模型)。我尝试在class_name中为模型命名空间,但它确实仍然在引擎中搜索模型。

错误

NameError: uninitialized constant Monologue::Post::MyApp::User

post.rb

class Monologue::Post < ActiveRecord::Base
  belongs_to :author, :class_name => "MyApp::User", :foreign_key => "author_id"
end

user.rb

class User < ActiveRecord::Base
  has_many :posts, :class_name => "Monologue::Post", :foreign_key => "author_id"
end

模式

create_table "monologue_posts", force: true do |t|
  t.integer  "author_id"
end

我使用了这个:Creating a belongs_to relationship with a model from the main app from an engine model

1 个答案:

答案 0 :(得分:0)

  

NameError:未初始化的常量Monologue :: Post :: MyApp :: User

您需要将user.rb 类名称 修复为MyApp::User

class MyApp::User < ActiveRecord::Base
  has_many :posts, :class_name => "Monologue::Post", :foreign_key => "author_id"
end