ruby-on-rails - 用户在注册时发布第一个嵌套帖子,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'))
有什么可以做的吗?如果有人知道,请告诉我。
解决方案
我做的。但如果有人知道更容易,请告诉我。
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
推荐阅读
- c - 使用 pthread 初始化互斥锁时出错
- javascript - React hook:如何在反应中从另一个组件调用模态组件
- spring-boot - 由于 JSP SpringBoot 中的位置,图像未加载
- html - 如何获得点击的tr的绝对位置?
- c - 为什么我的程序在我按 ctrl + D 时会在它结束之前打印一些东西?
- python - Beautiful Soup 仅从 Yahoo! 返回 100 行!金融
- laravel - 如何在公共 github 存储库中保持 Laravel .env 文件的安全
- javascript - 尝试查询按钮元素的路径时获取 Null
- python - 全局变量 X 未定义错误 | Python 逻辑错误
- c - 提取 uint8 的前 3 位