通过调用控制器方法Rails数据库种子

时间:2017-02-24 21:59:25

标签: ruby-on-rails seeding

我想用一些" League"楷模。在我的leagues_controller中,create方法不仅创建了联盟,还调用了许多与每个联盟模型相关的初始化方法。据我所知,当我在db / seeds.rb中进行方法调用时,控制器方法实际上没有被调用(我通过运行我目前在seeds.rb中所拥有的内容来确认,并且注意到各种初始化方法没有运行)。

有什么方法可以简单地在seeds.rb中调用控制器创建方法,这样我就不必重复代码了吗?

以下是一个例子:我想创建100个联赛。当一个联盟被创建时,我会用帮助方法创建球员和球队。我想简单地将league.create称为100次,而不用担心还会创建球队和球员。这是我的代码:

分贝/ 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
}

我的leagues_controller(我简化了代码以便于阅读):

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

1 个答案:

答案 0 :(得分:4)

一个好的解决方案是在模型中使用回调。所以在联盟模型文件中,您执行以下操作。

after_save :create_team_players, :create_teams

此功能现在将在创建操作 seed.rb

中调用