我的代码是这样的:
def index
@monkeys = Monkey.where(owner: current_user)
end
def new
@monkey = Monkey.new name: 'Monkey 1', alive: true, owner: current_user
end
def create
@monkey = Monkey.create monkey_params
# Other fields and save here
end
def edit
@monkey = Monkey.find_by(id: params[:id], owner: current_user)
check_on_monkey_first(@monkey)
end
def update
@monkey = Monkey.find_by(id: params[:id], owner: current_user)
check_on_monkey_first(@monkey)
if @monkey.update(monkey_params)
redirect_to monkeys_path, success: 'Monkey saved'
end
end
private
def check_on_monkey_first(monkey)
redirect_to monkeys_path, flash: {info: "Monkey doesn't exist"} and return unless monkey
redirect_to monkeys_path, flash: {info: "Monkey no longer exist"} and return if !monkey.alive?
end
def monkey_params
# some_fields_here
end
我认为“...并返回”只是提早退出 check_on_monkey_first
,然后继续 update
。
如果我不是 Monkey
的所有者,find_by
将不会获得记录并且应该执行 redirect_to
因为 猴子
将不存在。但它仍然继续并在 if @monkey.update(monkey_params)
处中断代码,因为 @monkey
为 nil。
如何在 Ruby 或 Rails 中执行“redirect_to some_path and return”?如何立即停止并执行 redirect_to?
最佳答案
可能有多种解决方案,但其中一种可能是返回一个 bool 值,表明您正在触发重定向。示例:
def update
@monkey = Monkey.find_by(id: params[:id], owner: current_user)
if check_on_monkey_first(@monkey) and @monkey.update(monkey_params)
redirect_to monkeys_path, success: 'Monkey saved'
end
end
private
def check_on_monkey_first(monkey)
redirect_to monkeys_path, flash: {info: "Monkey doesn't exist"} and return false unless monkey
redirect_to monkeys_path, flash: {info: "Monkey no longer exist"} and return false if !monkey.alive?
return true
end
更简洁的解决方案可能是对某些操作使用类似 before_action
(或 before_filter
for Rails < v4)的东西。但是,对于要在哪里执行 check_on_monkey_first
检查,它可能会降低您的灵 active 。对于您的特定用例,您可以尝试:
before_action :check_on_monkey_first, only: [:edit, :update]
然后将您的 check_on_monkey_first
修改为:
def check_on_monkey_first
@monkey = Monkey.find_by(id: params[:id], owner: current_user)
redirect_to monkeys_path, flash: {info: "Monkey doesn't exist"} and return unless @monkey
redirect_to monkeys_path, flash: {info: "Monkey no longer exist"} and return if !@monkey.alive?
end
您的更新
操作将变为:
def update
if @monkey.update(monkey_params)
redirect_to monkeys_path, success: 'Monkey saved'
end
end
这样您就可以删除需要它的操作中的检查(编辑和更新),您不必处理双重重定向,它应该会自动为您设置这些操作的变量。
关于ruby-on-rails - 如何做 "redirect_to and return"完全退出或立即 redirect_to?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22341604/