You can add a change event listener to your collection_select, and this way, whenever the user changes makes a change in the selection, then you can make your request to the method you need in the controller you need.
Give an id to your collection_select, and add the data attribute data-user (as example):
<%= collection_select(
:user,
:role_id,
User.roles,
:first,
:first,
{},
{'data-user': 1}
) %> # Skipping the "on-tag" onChange attribute
Then you can create an script to get the rendered select tag, add the change event listener, get the role and user values, and make an XMLHttpRequest, passing those values as JSON, in a POST request:
<script>
let role_select = document.getElementById('user_role_id')
role_select.addEventListener('change', function() {
let role = this.value,
user = this.dataset.user,
xhr = new XMLHttpRequest()
xhr.open('POST', '/test', true)
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
// Do whatever you want if it succeeds
} else {
// Do whatever you want if it doesn't succeed
}
}
xhr.send(JSON.stringify({role_id: role, user_id: user}))
})
</script>