Home > Mobile >  User make first nested post when register, Ruby on rails
User make first nested post when register, Ruby on rails

Time:09-16

I am making rails app, and I want when user register, user make first nested post automatically. I use Devise gem.

My model

class User < ApplicationRecord
  has_many :posts
end

class Post < ApplicationRecord
  belongs_to :user
  has_many :comments
end

class Comment < ApplicationRecord
  belongs_to :post
end

My Devise user registrations controller

class Users::RegistrationsController < Devise::RegistrationsController
  after_action :auto_generate_post, only: [:create]
  
  def auto_generate_post
    Post.create(title: 'Test post', content: 'This post is posted by automatically.', user_id: resource.id)
  end
end

I can make post, but I can't make comment. I've tried this

Post.create(title: 'Test post', content: 'This post is posted by automatically.', user_id: resource.id, resource.comments.build(comment: 'test comment'))

Is there anything to do this? If somebody knows it, please advise me.

CodePudding user response:

All of the devise controllers yield so you can "tap into" the superclass implementation simply by passing a block:

module Users
  class RegistrationsController < Devise::RegistrationsController
    def create
       super do |user|
         user.posts.create!(
           title: 'Test post', 
           content: 'This post is posted by automatically.'
         )
       end
    end
  end
end

Devise::RegistrationsController#create yields right after the user is created successfully but before the response is sent.

You should generally prefer building records off an assocation instead of passing ids explicitly as that leaks the implementation details from the model into the controller.

CodePudding user response:

I made this. But if somebody knows easier, please advise me.

first_post = Post.create(title: 'Test post', content: 'This post is posted by automatically.', user_id: resource.id)
first_comment_post = first_post.comments.build(comment: 'test comment')
first_comment_post.save
  • Related