I’m super frustrated by this one, because I’ve got to be doing something obviously wrong – but I can’t seem to figure out what!
Basically, I’m trying to add validation to a model. When I test the validation in the console, none of the validators I’ve set up seem to work!
Here’s the model in question:
class Sale < ActiveRecord::Base
validates :product, :presence => true
validates :variant, :presence => true
validates :price, :presence => true
validates :start, :presence => true
validates :end, :presence => true
belongs_to :shop
end
Here’s my console output:
1.9.2-p290 :008 > s = Sale.new
=> #<Sale id: nil, product: nil, variant: nil, start: nil, end: nil, price: nil, shop_id: nil, created_at: nil, updated_at: nil, compare_at: nil>
1.9.2-p290 :009 > s.valid?
=> true
1.9.2-p290 :010 > s.save
SQL (1.2ms) INSERT INTO "sales" ("compare_at", "created_at", "end", "price", "product", "shop_id", "start", "updated_at", "variant") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) [["compare_at", nil], ["created_at", Fri, 27 Jan 2012 02:06:40 UTC +00:00], ["end", nil], ["price", nil], ["product", nil], ["shop_id", nil], ["start", nil], ["updated_at", Fri, 27 Jan 2012 02:06:40 UTC +00:00], ["variant", nil]]
=> true
Now, if I understand this article correctly, valid? should return false because several of the object’s attributes are nil, when the model defines that they shouldn’t be – but it’s not!
Any ideas?
It turns out the error here was right in my face.
I had an addition file named Sale.rb, in a folder called jobs. This file re-opened the Sale class and added additional functionality relating to the
Delayed_Jobmodule. For an undetermined reason, this prevented the model validations from working or responding to methods likevalid?. To resolve this, I simply added the methods I had written in this separate file, and concatenated them into model\Sale.rb.