I have custom attribute setter in a Rails model in which i'm adding validation errors. However when record attributes are being updated 'true' returns as result, which kinda confusing to me. Any hints how to use validation errors inside custom setter?
Model:
class Post < ActiveRecord::Base
attr_accessible :body, :hidden_attribute, :title
def hidden_attribute=(value)
self.errors.add(:base, "not accepted")
self.errors.add(:hidden_attribute, "not_accepted")
write_attribute :hidden_attribute, value unless errors.any?
end
end
Console Output:
1.9.3p194 :024 > Post.last
Post Load (0.2ms) SELECT "posts".* FROM "posts" ORDER BY "posts"."id" DESC LIMIT 1
=> #<Post id: 1, title: "asdsaD", body: "la", hidden_attribute: nil, created_at: "2013-11-13 16:55:44", updated_at: "2013-11-13 16:56:06">
1.9.3p194 :025 > Post.last.update_attribute :hidden_attribute, "ka"
Post Load (0.2ms) SELECT "posts".* FROM "posts" ORDER BY "posts"."id" DESC LIMIT 1
(0.0ms) begin transaction
(0.0ms) commit transaction
=> true
I've made an example application for this case.
Okay, i understood the core of the issue. It's not possible to do what i want to achieve, because all the validations errors cleared out as soon as validation process starts.
Custom setter kicks in way too early :(