Ruby on rails RubyonRails:是否可以扩展一个方法而不重写它?
我想更改create方法的重定向,但我不想覆盖整个过程 比如,默认情况下,如果create(比方说)存在,它将有如下内容Ruby on rails RubyonRails:是否可以扩展一个方法而不重写它?,ruby-on-rails,Ruby On Rails,我想更改create方法的重定向,但我不想覆盖整个过程 比如,默认情况下,如果create(比方说)存在,它将有如下内容 respond_to do |format| if @user.save(params[:user]) flash[:notice] = 'The user has been updated' format.html { redirect_to :controller => "subscriptions",
respond_to do |format|
if @user.save(params[:user])
flash[:notice] = 'The user has been updated'
format.html { redirect_to :controller => "subscriptions",
:action => "show",
:id => @user.account_id }
format.xml { head :ok }
else
format.html { render :action => :edit }
format.xml { render :xml => @user.errors, :status => :unprocessable_entity }
end
end
或者类似的事情
但是它说format.html的地方。。。
我希望能够将继承此方法的类中的重定向\u更改为。。。但我不想重写整件事=\
想法?如果您知道原始方法采用的参数,可以调用
super
方法
class Foo
def foo(arg)
arg*2
end
end
class Bar < Foo
def foo(arg)
super(arg) + 3
end
end
a = new Foo
a.foo(2) # => 4
b = new Bar
b.foo(2) # => 7
class-Foo
def foo(arg)
arg*2
结束
结束
类Bar4
b=新杆
b、 foo(2)#=>7
调用super不会解决您的问题,因为您希望更改方法的内部工作方式,而不是传递新参数或向其添加代码
我要做的是创建第三个具有公共功能的函数(我们称之为common_例程)。然后从需要访问它的两个地方调用common_例程。但是,要根据需要更改代码,您需要传递一个块,并在方法内部生成该块以修改方法的工作方式
例如:
def common_routine
respond_to do |format|
if @user.save(params[:user])
flash[:notice] = 'The user has been updated'
format.html { yield }
format.xml { head :ok }
else
format.html { render :action => :edit }
format.xml { render :xml => @user.errors, :status => :unprocessable_entity }
end
end
end
然后你用以下方式来称呼它:
common_routine { redirect_to :controller => "subscriptions", :action => "show", :id => @user.account_id }
或
传递给common_例程的代码块将被“屈服”,这允许您在需要时进行细微调整以获得相同的功能。为什么要这样做?你的目标是什么?请解释更多。提供一些代码。我们需要做点什么来解决你的问题。
common_routine { redirect_to root_path }