I know, I know, they're not allowed to. But here's my problem. I've got
a really simple model with two fields, name and price, which I want to
show in a form select drop-down. "collection_select" takes a
'text_method' parameter, which is the method in the model that gets its
value placed in the <option> tag.
Because I want to show both name and price, I had to add an extra method
in my model-
def description
"#{name} - #{number_to_currency(price)}"
end
But this fails, because now I'm trying to reference number_to_currency
(a helper method) from my model. How can I get around this?
But this fails, because now I'm trying to reference number_to_currency
(a helper method) from my model. How can I get around this?
Well.. as you said it's not the best idea since you are somehow breaking the rules of MVC by using methods which are supposed to be only used by the views.
That said, a helper is just a ruby module, meaning you can use it in any class you want if you just include it. The only problem you can find is that some helper methods will assume they are running in a normal controller-view cycle (as they should), and they will try to use some of the magic variables that get instantiated automatically behind the scenes (such as the request, for example).
In case the helper you want to use doesn't try to use any of those variables, you should be able to just include the helper module in your model and use all the included methods directly.
Agreed, I'd rather not break MVC, which is why I'm a little frustrated
with collection_select for referencing the *model* for what should be
displayed in the select box... *grumble*
In any case, thanks very much, your solution works.
If you can come up with a way to integrate that with collection_select,
I'm all ears. But collection_select seems to reference the model
directly for display, which kind of breaks MVC.