Search code examples
ruby-on-railsseeding

Rails database seeding by calling controller methods


I would like to seed my testing database with a number of "League" models. In my leagues_controller, the create method not only creates the league, but also calls a number of initialization methods that are pertinent to each league model. As far as I'm aware, when I make a method call in db/seeds.rb, the controller method isn't actually called (which I confirmed by running what I currently have in my seeds.rb, and noting that the various initialization methods did not run).

Is there any way I can simply call the controller create method in seeds.rb so that I don't have to duplicate code?

Here's an example: I would like to create 100 leagues. When a league is created, I create players and teams to go along with it, in helper methods. I would like to simply call league.create 100 times, and not worry about also creating the teams and players. Here's my code for that:

db/seeds.rb:

number = 1
number_of_teams = 8
100.times {
    league_name = "Seed" + number.to_s
    if number > 33
        number_of_teams = 10
    elsif number_of_teams > 67
        number_of_teams = 12
    end
    # Needs to be modified, we want to call the controller method
    LeaguesAndTeams::League.create(name: league_name, number_of_teams: number_of_teams)
    number += 1
}

And my leagues_controller (I've simplified the code for easy reading):

def create
        @league = LeaguesAndTeams::League.new(league_params)
        puts "In the league create method"
        respond_to do |format|
            if @league.save
                # Initialization: I know this isn't the best idea to have them here, I simply put it here for demonstration purposes.
                create_team_players
                create_teams

                # Successful creation, redirect
                format.html { redirect_to leagues_and_teams_league_path(@league.id), notice: 'League was successfully created.' }
                format.json { render :show, status: :created, location: @league }
            else
                format.html { render :new }
                format.json { render json: @league.errors, status: :unprocessable_entity }
            end
        end
    end

Solution

  • A good solution is to use callbacks in your model. So in the league model file you do the following.

    after_save :create_team_players, :create_teams
    

    this functions now will be called in both create action and your seed.rb