I have this class:
class User
include Mongoid::Document
field :revenues, :type => Integer, :default => nil
attr_accessible :revenues
#now method
def revenues
return 1
end
end
Why in console I get 1 instead nil?
1.9.3-p125 :002 > u.revenues
=> 1
Which has priority, the method or the field? How can I created a method with the same features that a field?
The
fieldmacro is defined in Mongoid::Document. It is neither a syntatic feature from Ruby nor from Rails.What’s happening with your code is the following:
fieldfunction creates for you some methods, one of them is calledrevenues.revenues, you are in effect overwriting the previously defined method, therefore making it useless.Short answer: I don’t understand a zip about Mongoid, but chances are that your field still exists even after you defined oce again a method named
revenues. The only drawback is that you cannot access it by callingmyUser.revenuesanymore.Try to make a test: access your field with the notation
some_user[:revenues]and see what happen 🙂Best regards