Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
...
like image 633
user24601 Avatar asked May 28 '26 16:05

user24601


1 Answers

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

like image 57
Aschen Avatar answered May 31 '26 05:05

Aschen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!