安装rvm,ruby和rails后,我在模型中编写了相同的代码验证
class Item < ActiveRecord::Base
attr_accessible :name, :description, :price, :weight
validates :price, :weight, numericality: {greater_than: 0} , presence: true
end
但是当我启动rails console并打印
时tem1 = Item.create(name: "d", price: 0, weight: 1)
我有错误
Loading development environment (Rails 3.2.13)
2.0.0p0 :001 > item1 = Item.create(name: "d", price: 0, weight: 1)
NoMethodError: undefined method `validates' for #<Class:0x007ffa968ec810>
from /Users/epoleshchuk/RailsProject/test2/vendor/bundle/gems/activerecord-3.2.13/lib/active_record/dynamic_matchers.rb:55:in `method_missing'
from /Users/epoleshchuk/RailsProject/test2/app/models/item.rb:5:in `<class:Item>'
from /Users/epoleshchuk/RailsProject/test2/app/models/item.rb:1:in `<top (required)>'
from /Users/epoleshchuk/RailsProject/test2/vendor/bundle/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:469:in `load'
from /Users/epoleshchuk/RailsProject/test2/vendor/bundle/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:469:in `block in load_file'
from /Users/epoleshchuk/RailsProject/test2/vendor/bundle/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:639:in `new_constants_in'
from /Users/epoleshchuk/RailsProject/test2/vendor/bundle/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:468:in `load_file'
from /Users/epoleshchuk/RailsProject/test2/vendor/bundle/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:353:in `require_or_load'
from /Users/epoleshchuk/RailsProject/test2/vendor/bundle/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:502:in `load_missing_constant'
from /Users/epoleshchuk/RailsProject/test2/vendor/bundle/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:192:in `block in const_missing'
from /Users/epoleshchuk/RailsProject/test2/vendor/bundle/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:190:in `each'
from /Users/epoleshchuk/RailsProject/test2/vendor/bundle/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:190:in `const_missing'
from (irb):1
from /Users/epoleshchuk/RailsProject/test2/vendor/bundle/gems/railties-3.2.13/lib/rails/commands/console.rb:47:in `start'
from /Users/epoleshchuk/RailsProject/test2/vendor/bundle/gems/railties-3.2.13/lib/rails/commands/console.rb:8:in `start'
from /Users/epoleshchuk/RailsProject/test2/vendor/bundle/gems/railties-3.2.13/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from scexit
另外gem install activesupport -v 3.2.13对我没有帮助。
Rails 3.2.13 ruby 2.0.0p0(2013-02-24修订版39474)[x86_64-darwin12.3.0] rvm 1.19.3(稳定)
答案 0 :(得分:0)
仔细阅读您的错误:
undefined method `validates'
在validates
之前看起来你有一些奇怪的Unicode字符,你需要删除它。
答案 1 :(得分:0)
即使我从未使用过该方法,也会得到类似类型的未知方法错误 启动rails服务器。 这可能是由于在控制器或模型类文件中错误添加了一些单词。检查您的应用程序,看看是否在不知情的情况下在类定义之前和之后添加了单词“validates”。