这么一段代码
# notifications.rb
class Notification < ActiveRecord::Base
attr_accessible :content, :checked
belongs_to :sender, class_name: User, foreign_key: :sender_id
belongs_to :receiver, class_name: User, foreign_key: :receiver_id
scope :new, where(checked: false)
end
# factories.rb
factory :notification do
checked false
content { "A test notification" }
sender user
receiver tester
end
尝试用 FactorGirl 来产生一个测试对象死活成功不了,在 Console 里面看是这样的
1.9.3p194 :001 > noti = FactoryGirl.create(:notification)
NoMethodError: Notification Load (0.2ms) SELECT "notifications".* FROM "notifications" WHERE "notifications"."checked" = 'f'
undefined method `checked=' for []:ActiveRecord::Relation
from /Users/nevill/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/relation/delegation.rb:45:in `method_missing'
from /Users/nevill/.rvm/gems/ruby-1.9.3-p194/gems/factory_girl-2.3.2/lib/factory_girl/proxy.rb:132:in `block in assign_object_attributes'
from /Users/nevill/.rvm/gems/ruby-1.9.3-p194/gems/factory_girl-2.3.2/lib/factory_girl/proxy.rb:131:in `each'
from /Users/nevill/.rvm/gems/ruby-1.9.3-p194/gems/factory_girl-2.3.2/lib/factory_girl/proxy.rb:131:in `assign_object_attributes'
from /Users/nevill/.rvm/gems/ruby-1.9.3-p194/gems/factory_girl-2.3.2/lib/factory_girl/proxy.rb:107:in `object'
from /Users/nevill/.rvm/gems/ruby-1.9.3-p194/gems/factory_girl-2.3.2/lib/factory_girl/proxy.rb:84:in `result_instance'
from /Users/nevill/.rvm/gems/ruby-1.9.3-p194/gems/factory_girl-2.3.2/lib/factory_girl/proxy/build.rb:11:in `result'
from /Users/nevill/.rvm/gems/ruby-1.9.3-p194/gems/factory_girl-2.3.2/lib/factory_girl/proxy/create.rb:5:in `result'
from /Users/nevill/.rvm/gems/ruby-1.9.3-p194/gems/factory_girl-2.3.2/lib/factory_girl/factory.rb:163:in `run'
from /Users/nevill/.rvm/gems/ruby-1.9.3-p194/gems/factory_girl-2.3.2/lib/factory_girl/factory.rb:47:in `run'
from /Users/nevill/.rvm/gems/ruby-1.9.3-p194/gems/factory_girl-2.3.2/lib/factory_girl/syntax/methods.rb:148:in `run_factory_girl_proxy'
from /Users/nevill/.rvm/gems/ruby-1.9.3-p194/gems/factory_girl-2.3.2/lib/factory_girl/syntax/methods.rb:63:in `create'
from (irb):1
from /Users/nevill/.rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.8/lib/rails/commands/console.rb:47:in `start'
from /Users/nevill/.rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.8/lib/rails/commands/console.rb:8:in `start'
from /Users/nevill/.rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.8/lib/rails/commands.rb:41:in `<top (required)>'
今天又仔细看了一下,忽然灵光一闪,把这句改了就成功啦
scope :unread, where(checked: false)
总结:起名是个大学问