【发布时间】:2015-07-29 06:49:33
【问题描述】:
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'
但我遇到了语法错误。
控制台希望我如何检查用户和主题是否存在?
【问题讨论】:
-
查看rails guides,您可以将 Post 模型重构为 this
标签: ruby-on-rails ruby validation rails-console pry