通过Rails控制台创建新帖子并传递验证

时间:2015-05-17 20:27:32

标签: ruby-on-rails ruby validation rails-console pry

Ruby新手在这里。我正在进行一项让我验证帖子的作业。这就是我的 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),我应该创建一个通过验证的新帖子。我没有问题传递标题和正文,但我试图理解如何将它传递给主题和用户的逻辑。我认为它想要一个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'

但我收到语法错误。

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

1 个答案:

答案 0 :(得分:2)

您可以像这样传递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。