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

问题描述:

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

错误

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

NameError: uninitialized constant 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 
+0

我将有调整我的应用程序代码中的每个用户实例都是MyApp :: User? – MicFin

+0

@MicFin你已经在'user.rb'的'Monologue :: Post'中定义了类名:'class_name =>“MyApp :: User”,所以你需要改变'user.rb'的类名以及 – Pavan

+0

重命名User类会打破Rails活动支持/Users/Mike/.rvm/gems/ruby-2.1.5/gems/activesupport-4.1.1/lib/active_support/dependencies.rb:481:in'load_missing_constant':无法自动加载常量用户,期望/Users/Shared/code/kindrdfood/RecRm/app/models/user.rb来定义它(LoadError) – MicFin