All threads / How do I prepopulate table data for a new registered user?

Ask A Question

Notifications

You’re not receiving notifications from this thread.

How do I prepopulate table data for a new registered user?

Alex R asked in Rails

I'm wondering how would one go about prepopulating certain data table for a new user? Let's say I have a table with posts and a table with likes, and when new a user registers I'd like to make it so that certain posts are automatically liked upon registration. Would appreciate any guidance and suggestion.

There's a couple options for this generally:

  1. You can do this in the registration controller right after a successful save.
  2. Or you can do this in the model after_create (which might be simplest). I'll show that one here:
class User < ApplicationRecord
    has_many :likes

    after_create :create_default_likes

    private

    def create_default_likes
        # Create your likes here
        [1,2,3].each do |id|
            likes.create post_id: id
        end
    end
end

For the controller version, you'd basically do the same thing just after the if user.save. If you use something like Devise, you'll have to override the controller to do that.

Awesome! Thank you very much!

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 38,558+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.