在 Rails 中调用 Rake::Task 会导致“不知道如何构建任务...”
尝试在控制器方法上集成一些Friendly_id gem 功能。
本质上,我有一个 Market 对象,它的 URL 是基于自定义方法创建的。由于它基于自定义方法,因此 Friendly_id 不会更新网址当 Market 对象更新时。 Friendly_id 确实提供了 redo_slugs rake 任务,但是当我从控制器中调用它时,它告诉我它无法构建该任务。在外部运行命令效果很好。
我的控制器的代码如下所示:
require 'rake'
require 'friendly_id'
class Admin::MarketsController < ApplicationController
def update
if @market.update_attributes(params[:market])
rake_market_slugs
end
end
protected
def rake_market_slugs
Rake::Task["friendly_id:redo_slugs MODEL=Market"].invoke
end
end
我错过了什么吗?或者我可以不在控制器内执行此操作吗?
谢谢。
Trying to integrate some friendly_id gem functionality on a controller method.
Essentially, I have a Market object, which has its URL created based on a custom method. Since it's based on a custom method, friendly_id won't update the URL when the Market object gets updated. Friendly_id does offer a redo_slugs rake task, but when I call it from within my controller, it tells me that it can't build the task. Running the command outside works just fine.
The code for my controller looks like this:
require 'rake'
require 'friendly_id'
class Admin::MarketsController < ApplicationController
def update
if @market.update_attributes(params[:market])
rake_market_slugs
end
end
protected
def rake_market_slugs
Rake::Task["friendly_id:redo_slugs MODEL=Market"].invoke
end
end
Am I missing something? Or can I just not do this inside my controller?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从控制器调用 rake 任务来更新模型对象是很糟糕的。查看该 rake 任务的代码,您可以看到
redo_slugs
只是运行delete_slugs
和make_slugs
任务。所以还有另一个理由不这样做。您将为表中的每个Market
生成 slugs,而不仅仅是您需要的那个。如果您查看 make_slugs 的代码,您会发现可以看到那里没有魔法。它所做的只是以 100 个块为单位加载模型对象,然后保存它们。
所以,这将是我要尝试的第一件事。只需重新加载并保存您的模型即可。之后,我需要查看一些日志才能进行更深入的挖掘。
Calling a rake task from a controller to update a model object is terrible. Looking at the code for that rake task, you can see that
redo_slugs
is simply running thedelete_slugs
andmake_slugs
tasks. So there's another reason not to do this. You'll be generating slugs for everyMarket
in your table, instead of just the one that you need.If you look at the code for make_slugs you can see that there's no magic there. All it does is load your model objects in blocks of 100 and then save them.
So, that would be the first thing I would try. Simply reload and save your model. After that, I'd need to see some logs to dig deeper.