Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a method in seeds.rb in Ruby On Rails

I am trying to add a method to my seeds.rb so that I don't have to write a bunch of verbose code. However, depending on the placement of the create_deliverable method I get one of two error messages when running db:setup.

When method is before call

rake aborted! private method 'create_deliverable' called for #

When method is after call

rake aborted! undefined method `create_deliverable' for #

Is it not possible to uses methods in seeds.rb? Am I somehow calling the method incorrectly (I've tried calling with and without the self.)?

Method

def create_deliverable(complexity, project_phase_id, deliverable_type_id)
  Deliverable.create(:name => (0...8).map{65.+(rand(25)).chr}.join,
      :size => 2 + rand(6) + rand(6),
      :rate => 2 + rand(6) + rand(6),
      :deliverable_type_id => deliverable_type_id,
      :project_phase_id => project_phase_id,
      :complexity => complexity)
end

Calling Code

@wf_project.project_phases.each do |phase|
  DeliverableType.find_by_lifecycle_phase(phase.lifecycle_phase_id).each do
    |type|
    self.create_deliverable("Low", type.id, phase.id)

    self.create_deliverable("Medium", type.id, phase.id)

    self.create_deliverable("High", type.id, phase.id)
  end
end
like image 430
ahsteele Avatar asked Nov 17 '09 18:11

ahsteele


People also ask

What is Seeds rb in rails?

Rails seed files are a useful way of populating a database with the initial data needed for a Rails project. The Rails db/seeds. rb file contains plain Ruby code and can be run with the Rails-default rails db:seed task.

How do I create a seed data in rails?

Creating some seeds First, you destroy all movies to have a clean state and add three movies passing an array to the create method. The seeds file uses Rails ActiveSupport, to use those handy Ruby X. ago statements to define dates. In the end, there's some feedback about the total movies created.

How do I run a ruby seed?

When the database is not ready yet, in other words, we want to create the database first, then we can go with rails db:setup to first run migrations and then seeding. And the last option is when we want to reset the database, rails db:reset will drop the database, create again, and seed the application.


2 Answers

Make sure you define the method before calling it:

def test_method
  puts "Hello!"
end

test_method
like image 134
Joe Stepowski Avatar answered Sep 19 '22 19:09

Joe Stepowski


If you're going to use self., use it on the method definition, not the call.

def self.create_deliverable(...)
    ...
end
...
create_deliverable("Low", type.id, phase.id)
...

It's my understanding that .rb files without a class definition get wrapped in an anonymous ruby class when they are run, so defining the method on self should work just fine.

like image 32
localshred Avatar answered Sep 21 '22 19:09

localshred