通过 Rails 控制台创建新的 post 并通过验证

Creating new post via Rails Console and passing validation

Ruby 这里是新手。我目前正在做一项让我验证 posts 的作业。这就是我的 post.rb 的样子:

class Post < ActiveRecord::Base
  has_many :comments
  belongs_to :user
  belongs_to :topic

  default_scope { order('created_at DESC') }

   validates :title, length: { minimum: 5 }, presence: true
   validates :body, length: { minimum: 20 }, presence: true
   validates :topic, presence: true
   validates :user, presence: true
end

使用控制台(我正在使用 Pry),我应该创建一个通过验证的新 post。我在传递标题和 body 时没有问题,但我试图了解如何为主题和用户传递它的逻辑。我认为它需要 user_id 或 topic_id 但我不清楚如何实现它。

如果我输入(故意省略用户和主题):

 [1] pry(main)> p = Post.new(title: 'Longer than 5', body: 'This is the body. There should be more than 20 characters here in order to pass validation')
 => #<Post:0x007fee71a12180
 id: nil,
 title: "Longer than 5",
 body:
  "This is the body. There should be more than 20 characters here in order to pass validation",
 created_at: nil,
 updated_at: nil,
 user_id: nil,
 topic_id: nil>
[2] pry(main)> p.valid?
=> false
[3] pry(main)> p.errors.full_messages
=> ["Topic can't be blank", "User can't be blank"]

我明白这个错误(用户和主题不能为空)。我尝试添加:

topic: 'This is my Topic', user: 'myuserid'

但是我遇到语法错误。

控制台希望我如何检查用户和主题是否存在?

您可以像这样传递 TopicUser 类 的实例:

topic = Topic.create
user = User.create
p = Post.create(title: 'Longer than 5', body: 'This is the body. There should be more than 20 characters here in order to pass validation', topic: topic, user: user)

或者您可以使用 ID:

topic = Topic.create
user = User.create
p = Post.create(title: 'Longer than 5', body: 'This is the body. There should be more than 20 characters here in order to pass validation', topic_id: topic.id, user_id: user.id)

数据库将存储 ID 的任何一种方式。