【问题标题】:Creating new post via Rails Console and passing validation通过 Rails 控制台创建新帖子并通过验证
【发布时间】: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'

但我遇到了语法错误。

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

【问题讨论】:

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2013-03-22
    • 1970-01-01
    • 2017-11-08
    • 1970-01-01
    • 1970-01-01
    • 2017-09-30
    • 1970-01-01
    • 1970-01-01
    • 2022-08-15
    相关资源
    最近更新 更多