0

Given I've defined this in the config/routes.rb

resource :products

If I want to access the route helpers such as product_path(self) to generate urls in the Model. How could I mixin those modules in ?

steveyang
  • 9,178
  • 8
  • 54
  • 80
  • 2
    If you're having trouble getting access to something in rails, there's a chance you are doing it wrong. Why should a model have any knowledge of a resource path in your app? What is the end goal? – maček Dec 24 '12 at 10:32
  • I have an transaction model, which I use to talk to payment gateway such as paypal. As paypal has its own format of request url, I want to encapsulate it in the model, instead of scatter it round in controllers. Thus I could call `transaction.go_paypal` in my controller. As some `return_url` needs to be generated by the routes helper, so I need to access it in my model. I am aware of this problem, but I cannot think another way to archieve that. – steveyang Dec 24 '12 at 16:07
  • There are 2 question like this in stackover flow so take a look of that http://stackoverflow.com/questions/7465083/rails-3-view-helper-method-in-model http://stackoverflow.com/questions/2706433/access-a-view-helper-for-a-model-in-rails – SSP Dec 24 '12 at 10:35

1 Answers1

3
class MyClass < ActiveRecord::Base
  include Rails.application.routes.url_helpers
end

or (without inclusion)

Rails.application.routes.url_helpers.product_path(self)
dimuch
  • 12,728
  • 2
  • 39
  • 23
  • @steven.yang, you never answered the question in my comment, but I suppose I can't help you if you don't want to be helped. Of course this works, but I highly doubt you actually need this. Code smell is smelly. – maček Dec 24 '12 at 10:38
  • steven.yang if this is exactly what you need, why not accept the answer? And secondly: what @maček says is completely correct. While this works it is horrendous and against MVC. Why do you need this inside a model? If you need a function that has access to the routes, why not create a helper-method instead? – nathanvda Dec 24 '12 at 15:35