如何解决Rails中的参数错误?

时间:2014-06-01 10:35:10

标签: ruby-on-rails-3 rspec

我正在使用Ruby 1.9.3和Rails 3.2.16。我正在阅读Michael hartl的Rails教程中的第10章。

当我运行bundle exec rspec spec/时,我收到了以下错误:

/home/james/.rvm/gems/ruby-1.9.3-p484@rails3/gems/activemodel-3.2.16/lib/active_model/validations/validates.rb:86:in `validates': You need to supply at least one validation (ArgumentError)

from /home/james/rails3.2/rails_projects/sample_app/app/models/micropost.rb:7:in `<class:Micropost>'

我的micropost.rb文件

class Micropost < ActiveRecord::Base
  attr_accessible :content

  belongs_to :user

  validates :content, presence: true, length: { maximum: 140 }
  validates :user_id

  default_scope order: 'microposts.created_at DESC'
end

我该如何解决这个错误?

谢谢。

1 个答案:

答案 0 :(得分:0)

错误本身提供解决此错误的线索。

在micropost.rb文件中,在presence: true之后添加validates :user_id代码。

您更新的 micropost.rb 文件如下所示:

class Micropost < ActiveRecord::Base
  attr_accessible :content

  belongs_to :user

  validates :content, presence: true, length: { maximum: 140 }
  validates :user_id, presence: true

  default_scope order: 'microposts.created_at DESC'
end

我认为这可以解决您的错误。