首页 > 解决方案 > 用户在注册时发布第一个嵌套帖子,Ruby on rails

问题描述

我正在制作 Rails 应用程序,我希望在用户注册时,用户自动制作第一个嵌套帖子。我使用设计宝石。

我的模型

class User < ApplicationRecord
  has_many :posts
end

class Post < ApplicationRecord
  belongs_to :user
  has_many :comments
end

class Comment < ApplicationRecord
  belongs_to :post
end

我的设计用户注册控制器

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

我可以发帖,但我不能发表评论。我试过这个

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

有什么可以做的吗?如果有人知道,请告诉我。

标签: ruby-on-rails

解决方案


我做的。但如果有人知道更容易,请告诉我。

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

推荐阅读