default value in methods
I have problems with default values. I don't know whether I'm stupid or doc is not good (you're not supposed to answer :D ) but I spend a lot of time for trivial things.
According to Wiki RailsBestPractices, it's a good idea to add a default value like that:
When I try to add a default value, I get an error:
def self.custom_find( id_to_find = 1 )
[edit: the query is ok without = 0 default value ]
parse error, unexpected ')', expecting '='
def self.find_query(category, type, city_id, price_min = 0, price_max)
sql conditions coming here...)
Did I miss something?
Only the last parameters can have default values. How would you call it otherwise?
find_query(:cat, :type, :city_id, ????, 100)
So ruby is expecting the last parameter to have a default value too. That's why it needs a =, instead of ):
def self.find_query(category, type, city_id, price_min = 0, price_max = 100000)
^ =, not )
thanks Fenrir2, it works but I find it weird as it's not mandatory, just a best practice.
Plus it's not used when the value is empty, it seems to work only with null values.
It's there so you can omit these arguments if you call your procedure. It is by no means a best practice, there are special cases where it is handy. Only use default values if it makes sense.
It is there so you can call your procedure this way:
And don't worry about the min/max price.
Foo.find_query(a_category, a_type, a_city_id)
You cannot do this for a parameter in the middle because it makes no sense to omit it if you have parameters after it.
Another use case is Rails' find. You can use:
Foo.find(23) => find row with id=23
So you can use the same method in multiple ways.
Foo.find(:first, :conditions => 'a = "b"')
thanks for the tips Fenrir2