只是好奇是否有人知道在Rails框架中使用什么Ruby技术来完成以下操作.
如果我不在index
Rails控制器上编写一个方法,如果URL匹配该路由,Rails仍将呈现索引视图文件.这是有道理的,因为我的控制器继承自父类,父类必须有自己的index
方法.
但是,如果我做的定义index
方法,并且只告诉它设置一个实例变量,但它仍然呈现相应的视图.例如:
def index
@weasels = Weasel.all
# If I omit this line, Rails renders the index anyway.
# If this behavior is defined in the parent class's index method,
# it seems that by overriding the method, my index wouldn't do it.
# I'm not explicitly calling super to get the method from
# ActionController::Base, but maybe Rails is doing something like that?
render :index
end
Run Code Online (Sandbox Code Playgroud)
在纯Ruby中,我希望必须调用super
才能获得该行为.
我假设Rails使用某种元编程技术来保证我的控制器方法会调用 …
我想问一下我是否应该在我的控制器中保留空方法(这是一个关于代码风格的问题):
before_action :set_project, only: [:show,:new]
def show
end
def new
end
Run Code Online (Sandbox Code Playgroud)
我应该保持这样或简单地删除节目和新动作
class ProjectController < ApplicationController
before_action :set_project
def index
#indexaction
end
def create
#createaction
end
Run Code Online (Sandbox Code Playgroud)
是否更加偏执?Rails Styleguide并不表示任何溶剂,只有:
def show
end
Run Code Online (Sandbox Code Playgroud)
比...更好
def show; end
Run Code Online (Sandbox Code Playgroud)