Accessing Rails RESTful routes in the model
To clean up my code I would like access t开发者_JAVA百科o the RESTful helpers in my Rails model. Something like:
users_path
etc.
Thanks.
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.
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.
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
精彩评论