如何在模型更新后执行控制器私有方法?
How to execute a controller private method after a model update?
我在控制器中创建了一个私有方法。
private
def update_mark
...
...
end
- 我希望每当记录更新到我们拥有的四个模型中的任何一个时调用我的私有方法。我们该怎么做?
- 我看了"after_save"或者"after_commit"都可以用。但我不确定,使用哪一个。
谁能给我提供一个例子,说明我们如何才能做到这一点?
在您的模型中(比方说 A、B)添加一个将实例标记为已更新的方法
#A
class A < ApplicationRecord
attr_reader :updated
after_update :mark_updated
private
def mark_updated
@updated = true
end
end
#B
class B < ApplicationRecord
attr_reader :updated
after_update :mark_updated
private
def mark_updated
@updated = true
end
end
使用控制器中标记为已更新的实例变量
class DummyController < ApplicationController
#after the action we call the private method
after_action :update_mark, only: [:your_method]
#this is the method where your update takes place
def your_method
@instance = klass.find(params[:id])
@instance.update
end
private
# this is a model decider method which can figure out which model needs to
# be updated
def klass
case params[:type]
when 'a'
A
when 'b'
B
end
end
def update_mark
if @instance.updated
#write code which needs to run on model update
end
end
end
我在控制器中创建了一个私有方法。
private
def update_mark
...
...
end
- 我希望每当记录更新到我们拥有的四个模型中的任何一个时调用我的私有方法。我们该怎么做?
- 我看了"after_save"或者"after_commit"都可以用。但我不确定,使用哪一个。
谁能给我提供一个例子,说明我们如何才能做到这一点?
在您的模型中(比方说 A、B)添加一个将实例标记为已更新的方法
#A
class A < ApplicationRecord
attr_reader :updated
after_update :mark_updated
private
def mark_updated
@updated = true
end
end
#B
class B < ApplicationRecord
attr_reader :updated
after_update :mark_updated
private
def mark_updated
@updated = true
end
end
使用控制器中标记为已更新的实例变量
class DummyController < ApplicationController
#after the action we call the private method
after_action :update_mark, only: [:your_method]
#this is the method where your update takes place
def your_method
@instance = klass.find(params[:id])
@instance.update
end
private
# this is a model decider method which can figure out which model needs to
# be updated
def klass
case params[:type]
when 'a'
A
when 'b'
B
end
end
def update_mark
if @instance.updated
#write code which needs to run on model update
end
end
end