Code & Clay Notes to self. Mainly Ruby/Rails.

Updating an element with AJAX and UJS

UJS makes AJAX super easy.

Here, I want to update an element in response to a POST request.

remote: true ensures that the form – which button_to generates – is submited by AJAX.

def base_tag_link(symbol: '-', body:, params: {}, css_class: 'badge')
    button_to "#{sanitize(symbol)} #{body}", send(request_view.to_sym, params), class: css_class, remote: true

My controller action is simple.

def create
  respond_to do |format|

All I need to do is then create create.js.erb file in the corresponding view directory.

        .innerHTML = "<%= escape_javascript(render 'shared/selected_tags') %>"

The partial is rendered to a string and the JS updates .selected-tags with it as its content.