Creating a belongs_to relationship with a model from the main app from an engine model

让人想犯罪 __ 提交于 2019-12-10 00:08:39

问题


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?


回答1:


In your association set the class name explicitly, including the namespace:

belongs_to :user, :class_name => "MyEngine::User"



回答2:


I dont know much about engines, but you use :: to refer to the root namespace, so you could use ::User I guess




回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!