英文:
How to use subfolder inside views with Ruby on Rails
问题
我遇到了这个错误:
uninitialized constant DogsBreeds
每次我尝试访问:animals.com/doberman
这是我的home_controller.rb:
class HomeController < ApplicationController
def page1
end
def page2
end
end
这是我的routes.rb:
scope module: "dogs_breeds" do
get "/doberman", to: 'home#page1'
get "/chihuahua", to: 'home#page2'
end
而我的视图文件夹组织如下:
views > home > dogs_breeds > page1.html.erb
我尝试创建了dogs_breeds_controller.rb,如下所示:
class DogsBreedsController < ApplicationController
def page1
end
def page2
end
end
但是仍然没有改变。
英文:
Im having this error:
`uninitialized constant DogsBreeds`
Everytime I try to access to: animals.com/doberman
This is my home_controller.rb:
class HomeController < ApplicationController
def page1
end
def page2
end
end
This is my routes.rb
scope module: "dogs_breeds" do
get "/doberman", to: 'home#page1'
get "/chihuahua", to: 'home#page2'
end
And my views folder is organized like this:
views > home > dogs_breeds > page1.html.erb
I have tryed to create the dogs_breeds_controller.rb
class DogBreedsController < ApplicationController
def page1
end
def page2
end
end
But nothing has changed.
答案1
得分: 1
在定义你的路由时,像这样:
scope module: "dogs_breeds" do
get "/doberman", to: 'home#page1'
get "/chihuahua", to: 'home#page2'
end
然后,Ruby on Rails 的命名约定要求你有一个名为 HomeController
的控制器,命名空间为 DogBreeds
,并且放置在一个名为 dog_breeds
的子文件夹中,就像这样:
# 在 app/controllers/dogs_breeds/home_controller.rb 中
module DogBreeds
class HomeController < ApplicationController
def page1
#...
end
def home2
#...
end
end
end
请参考官方 Rails 指南中的 Rails Routing from the Outside In。
英文:
When defining your routes, like this
scope module: "dogs_breeds" do
get "/doberman", to: 'home#page1'
get "/chihuahua", to: 'home#page2'
end
then Ruby on Rails' naming conventions expect you to have a HomeController
controller namespaced with DogBreeds
and placed in a dog_breeds
subfolder like this:
# in app/controllers/dogs_breeds/home_controller.rb
module DogBreeds
class HomeController < ApplicationController
def page1
#...
end
def home2
#...
end
end
end
See Rails Routing from the Outside In in the official Rails Guides.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论