random_user_0891
random_user_0891

Reputation: 2051

rails 7 pass params when checkbox clicked

I'm trying to find a way to send params to a controller action when a checkbox is clicked in a Rails 7 web app. However, I don't have any form that gets submitted. The checkbox will be used to filter items in the index view.

I don't want to use jQuery/AJAX if possible, I have Stimulus/Hotwire in the web app so if there is a way to incorporate Stimulus that's also an option.

I currently have a link that handles sending param's to the controller, but I would like to replace it with a checkbox.

<%= link_to "red", cars_path(request.params.merge(color: 'red')) %>

I tried using onclick but couldn't get it working.

 <%# check_box_tag(:color, "red", checked=false, { disabled: false, onclick: "#{cars_path(request.params.merge(color: "red"))}" }) %>

Upvotes: 0

Views: 225

Answers (1)

Les Nightingill
Les Nightingill

Reputation: 6156

Here's how to do it... In your view (I use haml, not html):

#cbt{'data-controller'=>'check', 'data-check-url-value'=>foobar_path}
  = check_box_tag :foo, :bar, {}, 'data-action'=>'change->check#informServer'

and in your controller:

import { Controller } from "@hotwired/stimulus"
import { get } from "@rails/request.js"

export default class extends Controller{
  static values={
    url: String
  }
  async informServer(){
    let options = {
      contentType: "application/json",
      headers: {},
      query: {offset: 0, count: 20 },
      responseKind: "turbo-stream"
    }
    const response = await get(this.urlValue, options)
  }
}

I don't know what kind of payload you want in the ajax get request... in the example the query string carries 'offset' and 'count' parameters, you will choose something appropriate to your context.

Upvotes: 2

Related Questions