1 of 1 people found this helpful
To override the initialization you can do something like this:
alias_method :orig_initialize, :initialize
def initialize( *args )
# Do your thing here.
orig_initialize( *args ) # call original initialization.
You can override attributes like this:
# You could for example make sure that this does not return nil.
@vars[ :name ]
def name=( val )
# Validation here?
@vars[ :name ] = val
This works, because Rhom uses the method_missing method to handle any attribute operations. So 'user.any_attribute' ends up in the method_missing method where the given value is stored in (or retrieved from) the @vars hash. Defining a method prevents this behavior, so you should store or retrieve the value yourself.
I'm not familiar with the validation gem, but that seems a little more fit for the job. But as you see, you can have all the customization on the models that you want.
Sorry, I missed your reply
Can you please explain how can I get this done, for example:
My records should have "State" field.
How using *args I can add State = "N/A" to the record that is being created?
My controller code is straightforward:
@asset = Asset.create(@params['asset'])
redirect :action => :index
If I redefine create in model
def create (*args)
How do I add the State?
The asterisk in '*args' is called the splat operator, which can be used to convert an array to separate parameters and back again. But it's not only useful for parameters, I could recommend you to read a little about it:
In the previous example it's just used to pass all given parameters to the 'orig_create', but you can do more. If you want the first parameter to be used in your create method and pass the rest to the original one, you could do this:
def create( my_param, *args )
do_something( my_param )
orig_create( *args )
This is not what I wanted exactly, but using data from your first post (thanks for opening my eyes on alias_method and overriding methods in Model) I was able to get the results I wanted (some init, placeholders and validation checks in accessors).
Now, I need to understand how to behave when the model is passed invalid data.
I can determine that it's invalid, what then - throw an exception and have my controller code handle it? Or is there a recommended way of handling it?
Throwing an exception is the first option I'd consider, or you could return a value to indicate success or failure.
It will depend on your app's goal and structure what the best option is. So that's up to you.
Well you could use some JS to validate. Will try to send you a validation demo app tommorrow.