By Kristian


2013-02-15 23:23:39 8 Comments

I'm working on a rake task for a Rails project which is separated into multiple engines. The task is located in the lib/tasks folder of the main Rails application, and is attempting to create a new Post from the Blog engine (engines/blog/app/models/post).

The engine file (blog/lib/blog/engine.rb) looks like:

module Blog
  class Engine < ::Rails::Engine
    isolate_namespace Blog
  end
end

So if I'm understanding correctly, referencing Blog::ModelHere is the correct syntax. Here's the rake task:

namespace :blog do
  desc "Import blog posts from old Wordpress site"
  task :import => :environment do
    # ... generating variables here  
    post = Blog::Post.create!(
        post.title = title,
        post.slug = title.parameterize,
        post.date = date,
        post.user_id = User.find_by_name(user).id,
        post.content = content,
        post.tags = tags
    )
  end
end

Returns...
undefined method 'title=' for nil:NilClass

It seems to choke on the Blog::Post call. I've tried ::Blog::Post as well, but that didn't seem to make much sense. I've also tried keeping it in blog/lib/tasks as an engine task, but I couldn't get that working either.

I've looked around SO and Github to see if anyone has code up for rake tasks within engines, but couldn't find anything concrete. Any ideas?

1 comments

@Cluster 2013-02-16 00:06:16

Your create! should be accepting a block to perform the assignments, what you have there is doing assignments then passing the result as arguments.

post = Blog::Post.create! do |post|
    post.title = title
    post.slug = title.parameterize
    post.date = date
    post.user_id = User.find_by_name(user).id
    post.content = content
    post.tags = tags
end

@Kristian 2013-02-16 00:13:53

Awesome. I definitely misread the returned error. You're a lifesaver!

Related Questions

Sponsored Content

7 Answered Questions

[SOLVED] How to run Rake tasks from within Rake tasks?

  • 2009-02-23 15:13:16
  • Arry
  • 142982 View
  • 411 Score
  • 7 Answer
  • Tags:   ruby rake

14 Answered Questions

[SOLVED] How to understand nil vs. empty vs. blank in Ruby

  • 2009-05-19 22:51:36
  • Arrel
  • 307285 View
  • 1136 Score
  • 14 Answer
  • Tags:   ruby-on-rails ruby

5 Answered Questions

[SOLVED] Difference between rake db:migrate db:reset and db:schema:load

18 Answered Questions

[SOLVED] How to pass command line arguments to a rake task

26 Answered Questions

19 Answered Questions

[SOLVED] Purge or recreate a Ruby on Rails database

6 Answered Questions

[SOLVED] Do rails rake tasks provide access to ActiveRecord models?

2 Answered Questions

[SOLVED] Include Rake tasks from a gem into my engine

3 Answered Questions

[SOLVED] Adding code to a model with a custom rake task

  • 2009-12-09 10:48:06
  • stephenmurdoch
  • 195 View
  • 1 Score
  • 3 Answer
  • Tags:   ruby-on-rails rake

Sponsored Content