0

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.

Kevin Whitaker
  • 12,435
  • 12
  • 51
  • 89

2 Answers2

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

Try it...
krunal shah
  • 16,089
  • 25
  • 97
  • 143
0

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.

jdl
  • 17,702
  • 4
  • 51
  • 54
  • Thanks so much for the help. Reloading and saving the model did exactly what I needed it to do. Out of curiosity, why is it a bad idea to invoke rake tasks from within the app? – Kevin Whitaker Sep 24 '10 at 20:39
  • Specifically, in this case, because what you're trying to do with that rake task was modify a model that you already had access to. Also, because the task that you were trying to run was massive overkill (update every record instead of just one). – jdl Sep 24 '10 at 21:03
  • They worked 4 years ago in 2010 when this was posted. Given that this site is a giant wiki, feel free to edit these URL's as you see fit. – jdl Jun 30 '14 at 15:10