Jack Kinsella
Jack Kinsella

Reputation: 4631

How to generate a rails link with an AR validation message

I'd like to give a link to the contact us page on failure of a validation. I've tried this to no avail:

validates_acceptance_of :not_an_agency, :on => :create,
:message => "must be confirmed. If you are an agency please #{link_to "Contact Us", contact_path}"

Anyone know how to get past this one?

Jack

Upvotes: 4

Views: 1033

Answers (3)

Bryan Larsen
Bryan Larsen

Reputation: 10006

Shingara's answer helps you with the "link_to" part, but it still crashes on the "contact_path" part. My solution:

validates_acceptance_of :not_an_agency, :on => :create,
                      :message => lambda {|e,f| "must be confirmed. If you are an agency please <a href=\"#{Rails.application.routes.url_helpers.contact_path}\">Contact Us</a>".html_safe}

I choose to just type <a href.../> rather than doing an include ActionView::Helpers::UrlHelper. That's up to you.

Also note the .html_safe. It's actually useless because Rails loses it when it adds the field name and you'll have to make it safe on the view side again. But I put it in anyways in the hope that Rails will eventually fix that piece of brokenness.

And I have no idea what the |e,f| are for. I had to put them in to fix up a silly argument number mismatch error.

Upvotes: 0

Giles Bowkett
Giles Bowkett

Reputation: 529

As of Rails 3.1 you can also do:

view_context.link_to "Contact Us", contact_path

Also, just to be strict, the original poster's code example is missing a close quote on "Contact Us"

Upvotes: 1

shingara
shingara

Reputation: 46914

With Rails 3

you need include ActionView::Helpers::UrlHelper in your Model and define the message like a lambda to be interpret when needed

class XXX < AR
  extend ActionView::Helpers::UrlHelper

  validates_acceptance_of :not_an_agency, :on => :create,
                          :message => lambda {"must be confirmed. If you are an agency please #{link_to "Contact Us", contact_path}"}

end

With Rails 2

it's the same but you need define the :host each time.

class XXX < AR
  extend ActionView::Helpers::UrlHelper

  validates_acceptance_of :not_an_agency, :on => :create,
                          :message => lambda {"must be confirmed. If you are an agency please #{link_to "Contact Us", contact_path(:host => 'http://example.org')}"}

end

Upvotes: 0

Related Questions