New to Ruby on Rails so this may be a stupid question. I have an app and I can bundle my gems without issue. So now I want to add some mostly static pages. I try to generate a controller for them with rails generate controller MostlyStatic page1 page2. This should generate a controller named mostly_static and pages named page1 and page2. Instead, I throw an error. Apparently the generate command is trying to connect to the database, which I have not yet created. There is nothing in these pages that should be a database table, so I'm a bit confused as to why the database is being brought into the process at this juncture. I've looked through various tutorials and none say that a database is required to generate controllers for static pages. So... what am I missing? Do I need to create the database first just to generate static pages? And, if so, will subsequently dropping any tables created by that generation impair the function of my app? I really don't want a bunch of useless tables for static pages hanging around. Is there a way to generate these pages and controllers without the database?
问问题
728 次
2 回答
3
您没有遵循生成控制器的约定。生成控制器不会创建数据库表。rails generate model
您必须通过调用或rails generate resource
来做到这一点rails generate scaffold
。
因此,您需要一个用于几个静态页面的控制器。尝试这个
rails generate controller static_pages home help contact
请注意生成器是复数和蛇形大小写(static_pages)。这将生成静态控制器和home.html.erb
, help.html.erb
, 和contact.html.erb
页面
现在您可以在控制器中使用这些操作访问页面
def home
end
def help
end
def contact
end
还需要确保设置了路线
# routes.rb
match '/home', to: 'static_pages#home'
match '/help', to: 'static_pages#help'
match '/contact', to: 'static_pages#contact'
没有设置数据库,您可以访问页面。这就是你需要做的所有事情。只需遵循约定,例如复数控制器和单数模型,并且 rails 负责处理细节。希望这能让你开始
更新
回应这里的评论是生成控制器的标准输出。请注意,我的示例使用 haml 而不是 erb,但输出中没有与数据库相关的内容。
rails g controller static_pages home help contact
create app/controllers/static_pages_controller.rb
route get "static_pages/contact"
route get "static_pages/help"
route get "static_pages/home"
invoke haml
create app/views/static_pages
create app/views/static_pages/home.html.haml
create app/views/static_pages/help.html.haml
create app/views/static_pages/contact.html.haml
invoke rspec
create spec/controllers/static_pages_controller_spec.rb
create spec/views/static_pages
create spec/views/static_pages/home.html.haml_spec.rb
create spec/views/static_pages/help.html.haml_spec.rb
create spec/views/static_pages/contact.html.haml_spec.rb
invoke helper
create app/helpers/static_pages_helper.rb
invoke rspec
create spec/helpers/static_pages_helper_spec.rb
invoke assets
invoke coffee
create app/assets/javascripts/static_pages.js.coffee
invoke scss
create app/assets/stylesheets/static_pages.css.scss
于 2013-06-12T00:17:46.663 回答
0
对于遇到这个问题的任何人,正确的答案是数据库不需要存在,但它必须正确配置,就好像它确实存在于配置文件中一样。生成控制器实际上并不创建数据库。
于 2013-07-29T19:41:40.187 回答