Using view helpers and route helpers in a model

Hi there,

I am trying to get something working and its driving me crazy. I have
been looking around for solutions to getting view helpers working in
models and for the most part I find this solution.

Add the following in the model you want to use them in

include ActionView::Helpers::UrlHelper
include ActionController::UrlWriter

However, when I try something like

link_to(polymorphic_path(@node)) I get an error.

“can’t convert String into Hash”

This is because ‘link_to’ uses ‘url_for’ which is a method that both
UrlHelper and UrlWriter both have which actually behave differently.

so my polymorphic_path(@node) => “/nodes/1” is a string and
ActionController’s url_for is expecting a hash.

Has anyone seem this and found a nice clean solution, or is this just
the wrong way to go about things

Cheers

RobL

There’s probably a workaround, but I’d agree that this is the wrong
way to do things. Generally, if you’re producing HTML in models
something has gone seriously awry…

–Matt J.

Thanks for the response Matt.

I don’t necessarily agree that using html in models is wrong. If I were
putting in lots of methods like

def link
link_to self.name, self
end

That would be quite bad, and more worthy of a view helper. But I am not
trying to DRY up the view indeed there is not even necessarily a request
involved when I intend to use the method. I am trying to use Facebooker
to publish status updates to Facebook and there is no controller or view
directly in play here. So in my controller an object is created and its
observer creates a series of events which eventually publishes a status
update to facebook which is text with a link in it.

I could render a view for what is basically 6 or 7 words but that seems
like overkill for something that is so (apparently) basic.

I’ll keep looking I guess

RobL

this may help


Oscar Del B.
Sent with Sparrow (http://www.sparrowmailapp.com/?sig)

Did you ever find an answer to this? I’m experiencing the same issue
with rails 2.3.x