solnic / virtus

[DISCONTINUED ] Attributes on Steroids for Plain Old Ruby Objects
MIT License
3.77k stars 229 forks source link

Prevent model from being created if there is any unknown attribute #337

Open tanapoln opened 9 years ago

tanapoln commented 9 years ago

For example,

class RegisterModel
    include Virtus.model(unknown: false)
    attribute :name, String
end

RegisterModel.new(name: "Ben Smith", mal_input: "---") #this should fail and raise error

neumachen commented 9 years ago

You can just override the initializer and do the logic there.

fr33z3 commented 8 years ago

I don't think that the behaviour when model raises exception when you are trying to get an instance of it is useful. Sounds like anti-pattern. Instead of that you should probably define some method named valid? to check if model is valid or not and then manually raise an exception.

zhulik commented 7 years ago

Sorry for necroposting, but it is default behavior in ActiveRecord and can really save you from typos in you code. I think optional mode with restricted unknown fields is a good idea.