views:

29

answers:

2

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.

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

Try it...
krunal shah
Unfortunately, it still errors out with "Don't know how to build task 'friendly_id:redo_slugs'"
Kevin Whitaker
@Kevin May be this link help you .. http://stackoverflow.com/questions/1170148/run-rake-task-in-controller
krunal shah
A: 

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
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
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