如何在Ruby on Rails中使用视图内的子文件夹

huangapple go评论59阅读模式
英文:

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 &lt; ApplicationController
  def page1

  end

  def page2

  end
end

This is my routes.rb

 scope module: &quot;dogs_breeds&quot; do
  get &quot;/doberman&quot;, to: &#39;home#page1&#39;
  get &quot;/chihuahua&quot;, to: &#39;home#page2&#39;
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 &lt; 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: &quot;dogs_breeds&quot; do
  get &quot;/doberman&quot;, to: &#39;home#page1&#39;
  get &quot;/chihuahua&quot;, to: &#39;home#page2&#39;
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 &lt; ApplicationController
    def page1
      #...
    end

    def home2
      #...
    end
  end
end

See Rails Routing from the Outside In in the official Rails Guides.

huangapple
  • 本文由 发表于 2023年7月17日 12:05:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76701421.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定