+1 to what Tobias said.
The Rails approach to MVC is to push a lot of things down into the
model.
Whether or not you think this is the right way to do things (which,
for the record, I don’t), you shouldn’t try to fight it when
developing Rails code.
Here’s an example from some code I’ve been working on lately to
illustrate the point:
I hate dropdowns, so I don’t want to use the standard date picker for
a date field on my model. I’d rather have a text field and parse the
date, but this obviously requires validation. So, here’s the code
from my model:
(Just take date_is_valid? and parse_date as givens for now.)
attr_writer :date_as_text
def date_as_text
@date_as_text ||= (date && date.strftime(‘%d %b %Y’)
end
validate :validate_date_as_text
def validate_date_as_text
if @date_as_text
if date_is_valid?(@date_as_text)
self.date = parse_date(@date_as_text)
else
errors.add(‘date’, must be a valid date’)
end
end
end
“But wait!”, I hear you cry, “Why are you doing this in your model?
It’s clearly a user interface issue, and belongs elsewhere!”
In theory, you’re absolutely right. In practice, Rails puts all
validations in the model and you’re best not to fight it.
Here’s what happens if I try to handle the date_as_text field in the
controller:
def new
@my_model = MyModel.new
if request.post?
date_is_valid = date_is_valid?(params[:date_as_text])
@my_model.date = parse_date(params[:date_as_text]) if
date_is_valid
if @my_model.valid? and date_is_valid
@my_model.save
else
@my_model.errors.add(‘date’, ‘must be a valid date’) unless
date_is_valid
end
end
end
I feel like I’m fighting Rails to pull this off. I’ve got to run the
model validations manually. I’ve got to push errors from the
controller back into the model so that they can be passed to the
view, and I’ve got to be careful to do it after I do the save. I
can’t really have model validations for the date field too, because
then the user might see multiple, conflicting errors for the one
field. Editing a record requires more code, because I have to grab
the date and convert it to text before displaying the form.
So, as much as I believe that code like this should live in the view/
controller, it’s not worth fighting the Rails way of doing things to
make my ideological point.
Pete Y.
http://9cays.com
On 05/05/2006, at 11:05 AM, Tobias Lütke wrote: