Jez Caudle
Jez Caudle

Reputation: 183

Accessing Rails RESTful routes in the model

To clean up my code I would like access to the RESTful helpers in my Rails model. Something like:

users_path

etc.

Thanks.

Upvotes: 12

Views: 8328

Answers (3)

te_chris
te_chris

Reputation: 631

Just to re-open this: For all rails 3+ users including UrlWriter won't work as it's deprecated. What does work though, is this:

include Rails.application.routes.url_helpers

Hope that helps anyone who stumbled onto this like I did.

Upvotes: 47

Allen Bargi
Allen Bargi

Reputation: 15172

class ActiveRecord::Base
 include ActionController::UrlWriter

 host = case ENV['RAILS_ENV']
 when "production"
   "yourlivedomain.com"
 when "development"
   "localhost:3000"
 end
 default_url_options[:host] = host
end

Upvotes: -3

John Topley
John Topley

Reputation: 115322

Why do you want to access routes in your model? This is a violation of the Model/View/Controller (MVC) pattern that is at the heart of Rails. Models shouldn't have any knowledge of routes which are a controller and view concern. Models should stand alone from the user interface.

If you told us what you are trying to achieve then we may be able to suggest a better approach.

Upvotes: -1

Related Questions