This strategy can be used for creating / removing associations between two objects in a Rails app using Ajax / UJS. For example, setting up tag associations (i.e., one tag name applied to many individual posts) or favorites (i.e., many users saving personal favorites against global objects).
It's designed to work in a list / table format, where you're creating and removing associations in a single page format. To initiate, make sure the list / table partial for each "owner" item contains the content from _item-partial.html.erb
. A similar setup should also work in non-list / table formats, as long as each instance of the owner artifact includes the classes and data attributes required by the JavaScript partials.
If using to modify a single field on a record (e.g., a boolean) rather than creating separate associations, the controller setup would need to be adjusted to work with the update
method on the "owner" class directly:
def update
@thing = Thing.find(params[:id])
if params[:attribute]
@thing.update(attribute: params[:attribute])
end
respond_to do |format|
if @thing.update(thing_params)
format.js
end
end
end
And links would need to supply method: :patch
:
<%= link_to thing_path(@thing, thing: { attribute: value} ), method: :patch, remote: true, class: 'thing-status save-thing', data: { turbolinks: false, thing_id: @thing.id } do %><i class="far fa-check-square"></i><% end %>
The create.js.erb
and destroy.js.erb
files could be consolidated to a single update.js.erb
file to accept either case.