Ruby on Rails model inside namespace can't be

2019-03-15 18:35发布

I'm new to rails and can't figure out this issue...

I have a controller

Admin::Blog::EntriesController

defined in app/controllers/admin/blog/entries_controller.rb

And I have a model called

Blog::Entry

defined in app/model/blog/entry.rb

When I try to access my model from the controller, I get a "uninitialized constant Admin::Blog::EntriesController::Blog" from this line:

@blog_entries = Blog::Entry.find(:all)

Clearly it is not finding the namespace correctly which is odd because according to what I have read, I have placed my model in the correct folder with the correct syntax.

Any ideas on how I can fix this?

Thanks

4条回答
男人必须洒脱
2楼-- · 2019-03-15 19:01

Yeah, from looking at the code form_for uses polymorphic_path under the hood.

查看更多
做自己的国王
3楼-- · 2019-03-15 19:03

It is now 2011 and we are in Rails 3.1 territory, but this issue still arises. I just ran into it with a namespaced controller referencing a non-namespaced model, but only when there were no rows for that model in the database!

Prefixing the model name with :: fixes the problem.

查看更多
迷人小祖宗
4楼-- · 2019-03-15 19:08

Try:

@blog_entries = ::Blog::Entry.find(:all)

It's currently looking for the wrong class. Using :: before Blog will force it to look from the top level.

查看更多
聊天终结者
5楼-- · 2019-03-15 19:08

You can achieve a custom table name by using

set_table_name('foo')

at the top of your model.

As for multiple namespaces, you might be able to get away with using

polymorphic_path(@the_object)

to generate your urls as it does more basic inference (in my experience at least, maybe form_for uses it under the hood).

查看更多
登录 后发表回答