【发布时间】:2022-11-09 23:38:55
【问题描述】:
我正在尝试学习 Ruby on Rails,但我有点陷入联想。 我的项目是用三个表创建一个简单的博客。用户、帖子和评论。
据我了解,在将几个表与外键关联后,rails 会自动找到 user_id 和 post_id。但是每次我尝试构建 cmets 时,user_id 都是 nil。
这是我的模型:
class User < ApplicationRecord
has_many :posts
has_many :comments
validates :name, presence: true, length: { minimum: 5 }, uniqueness: true
validates :password, presence: true, length: { minimum: 5 }
end
class Post < ApplicationRecord
belongs_to :user
has_many :comments
validates :title, presence: true
validates :body, presence: true, length: {minimum: 10}
end
class Comment < ApplicationRecord
belongs_to :post
belongs_to :user
validates :body, presence: true
validates :user_id, presence: true
validates :post_id, presence: true
end
如您所见,post_id 不是 nil,但 user_id 是 nil。
我尝试手动输入用户 ID,它按预期工作。但我不知道如何使用自动用户 ID 和 post_id 创建评论。
【问题讨论】:
-
您能在此处添加有问题的
comments_controller代码吗? -
啊,对不起,这个练习需要用控制台来解决。
-
你可以试试这个
comment = post.comments.build(user_id: user.id)。参考答案
标签: ruby-on-rails ruby database activerecord