在 Rails 中调用 Rake::Task 会导致“不知道如何构建任务...”

发布于 2024-09-24 16:47:42 字数 746 浏览 6 评论 0原文

尝试在控制器方法上集成一些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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

野稚 2024-10-01 16:47:42

从控制器调用 rake 任务来更新模型对象是很糟糕的。查看该 rake 任务的代码,您可以看到redo_slugs只是运行delete_slugsmake_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 the delete_slugs and make_slugs tasks. So there's another reason not to do this. You'll be generating slugs for every Market 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.

安稳善良 2024-10-01 16:47:42
def rake_market_slugs
   MODEL="Market"
  Rake::Task["friendly_id:redo_slugs"].invoke(MODEL)
end

Try it...
def rake_market_slugs
   MODEL="Market"
  Rake::Task["friendly_id:redo_slugs"].invoke(MODEL)
end

Try it...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文