0

I am using Rails with React in my app, and I wanted to pass url for Post model in as_json method. It has been working correctly with this method found on SO, where I pass the locale and the id (or self.id):

Rails.application.routes.url_helpers.post_path(locale, id)

I have now included FriendlyID gem in my project and I can go to my post page using the generated slug, but the method above still returns the old URL with ID. My question is - how can I change that?

PS I can do just (code below), but was wondering if there is an easier way?

...posts_path(locale) + "/#{slug}"
mdmb
  • 4,833
  • 7
  • 42
  • 90
  • Use [ActiveModel::Serializers](https://github.com/rails-api/active_model_serializers) or jbuilder instead of monkeying around with the `.to_json` method. I would argue that models should not be aware of the current locale or anything request related. – max Apr 24 '17 at 22:07

1 Answers1

4

The correct way (and the way Rails was designed to do it) is

Rails.application.routes.url_helpers.post_path(locale, to_param)

the to_param method by default returns the :id as a string but is overridden by people who use slugs directly or via gems like friendlyID

SteveTurczyn
  • 36,057
  • 6
  • 41
  • 53