我正在制作rails應用程式,我希望當用戶注冊時,用戶能自動發表第一個嵌套帖子。我使用Devise gem。
我的模型
class User < ApplicationRecord
has_many :post
end
class Post < ApplicationRecord
belongs_to:user
has_many :comments
end
class Comment < ApplicationRecord
belongs_to :post
end
我的Devise用戶注冊控制器
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
我可以發帖,但我不能發表評論。我試著這樣做了
Post.create(title: 'Test post', content。'這個帖子是自動發布的。', user_id: resource.id, resource.comments.build(comment: 'test comment'))
有什么辦法可以做到這一點嗎?如果有人知道,請告訴我。
uj5u.com熱心網友回復:
所有的devise控制器都是屈服的,所以你可以通過傳遞一個塊來 "進入 "超類的實作:
module Users<
class RegistrationsController < Devise:: RegistrationsController
def create
super do |user|
user.post.create!(
title: 'Test post'。
content: 'This post is posted by automatically.
)
結束。
end
end end
end end
Devise::RegistrationsController#create在用戶創建成功后但在發送回應之前產生。
一般來說,你應該傾向于從assocation中建立記錄,而不是明確地傳遞id,因為這樣會將模型中的實作細節泄露給控制器。
uj5u.com熱心網友回復:
我做了這個。但如果有人知道更簡單的,請告訴我。
first_post = Post.create(title: 'Test post', content: '這個帖子是自動發布的。', user_id: resource.id)
first_comment_post = first_post.comments.build(comment: 'test comment')
first_comment_post.save
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/307031.html
標籤:
上一篇:覆寫setter屬性不呼叫
