Search code examples
ruby-on-railsrubyseeding

Rails - In-app "database seed" button?


I'm building a Rails app for my company. My seeds.rb file contains code to sync my list of users with our Office 365 directory, which needs to happen every time something changes in the directory, and I'm trying to build an in-app "seed" button so that people with no Rails/Heroku knowledge can initiate that process.

As you can see in the code excerpts below, I've figured out that I can do this by calling rails db:seed as a shell command, but it feels like there should be a less roundabout way to do this than a Rails app calling a shell command to perform an operation on itself.

Is there a way to actually run the code in seeds.rb from within the app, or is calling rails db:seed the closest I've got?

app/views/layouts/_header.html.erb

...
<li><%= link_to "Sync users with O365", seed_path %></li>
...

config/routes.rb

...
get '/seed', to: 'application#seed'
...

app/controllers/application_controller.rb

...
  def seed
    `rails db:seed`
    redirect_back_or root_path
  end
...

Solution

  • You can simply use Rails.application.load_seed where you want in your code