Rails URL helpers from Stimulus controller?

Viewed 1520

Simple question, what's the correct way of accessing URL helpers from inside a stimulus controller?

Right now we're having to do some rather smelly code where the controller gets passed though erb, to allow something like this:

// app/javascript/controllers/stage_filter_controller.js.erb

import { Controller } from 'stimulus'

export default class StageFilterController extends Controller {

  // snip...

  getPlotsUrl(siteId) {
    var url = '<%= Rails.application.routes.url_helpers.plot_options_path %>'
    url += `?site=${siteId}`
    return url;
  }
}

I don't like this at all, but don't know how to do it any other way.

1 Answers

You use the path_helper in the view and set a dataset object to that value. Then access it in the Stimulus controller.

# view

<span data-url="<%= plot_options_path %>" data-target="stage-filter.link">
</span>


# app/javascript/controllers/stage_filter_controller.js.erb

import { Controller } from 'stimulus'

export default class StageFilterController extends Controller {
  static targets = ['link']

  getPlotsUrl(siteId) {
    var url = this.linkTarget.dataset["url"]
    url += `?site=${siteId}`
    return url;
  }
}

You wouldn't actually need another DOM object (ie. the span). You could use the div(?) your controller is sitting in, too, or any other target you already have.

Related