我想问一下我是否应该在我的 Controller 中保留空方法(这是一个关于代码风格的问题):
before_action :set_project, only: [:show,:new]
def show
end
def new
end
我应该保持这样还是简单地删除节目和新 Action
class ProjectController < ApplicationController
before_action :set_project
def index
#indexaction
end
def create
#createaction
end
是不是更 Railish 的方式? Rails Styleguide 没有表明任何解决方案,只是:
def show
end
比
def show; end
最佳答案
如果您没有在这些方法中定义任何数据,则可以删除它们。
Rendering By Default:
Rails 会自动从路由中的操作名称推断 View 。
如果您没有定义数据(只能在 Controller 中完成),您可以依赖 view
正在加载 没有 出现的 Action :
You've heard that Rails promotes "convention over configuration". Default rendering is an excellent example of this. By default, controllers in Rails automatically render views with names that correspond to valid routes. For example, if you have this code in your
BooksController
class:class BooksController < ApplicationController end
And the following in your routes file:
resources :books
And you have a view file
app/views/books/index.html.erb
:<h1>Books are coming soon!</h1>
Rails will automatically render
app/views/books/index.html.erb
when you navigate to /books and you will see "Books are coming soon!" on your screen.
好引用:Rails doesn't need index method in controller defined?
关于ruby-on-rails - Controller 中的 Rails 空方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35358521/