I've built myself a Rails Engine that requires that the main app have a Users table. I need to be able to create a relationship between one of the models in my engine and the Users table in the main app. Is this more complicated than just saying belongs_to :user
? I'm getting an error that says the User
object is nil, but when I use the console it returns the right user. My assumption is that Rails assumed my belongs_to :user
call meant a User's class in the same namespace as the engine, i.e. MyEngine::User. Is there a way for me to explicitly specify that the User class is in the main app's namespace and not the engine's?
In your association set the class name explicitly, including the namespace:
belongs_to :user, :class_name => "MyEngine::User"
I dont know much about engines, but you use ::
to refer to the root namespace, so you could use ::User
I guess
Turns out the engine recognizes the MainApp's user class by default just by saying belongs_to :user. I was doing something else wrong :/.
来源:https://stackoverflow.com/questions/11707639/creating-a-belongs-to-relationship-with-a-model-from-the-main-app-from-an-engine