matiss matiss - 1 month ago 12
Ajax Question

Rails 5: update action not working for AJAXified form

I have view with dropdown where on user select, particular user role can be edited.

In /common/roles/index.erb I have this:

<form class="form-horizontal" role="form" method="get" action="/common/roles" data-remote="true">
<div class="col-sm-10"><select class="form-control m-b" name="users" id="user_list">
<option value="">Please, select user</option>
<% @users.each do |user| %>
<% for role in user.roles %>
<option value="<%= role.id %>"><%= user.name %></option>
<% end %>
<% end %>
</select>
</div>
</form>
<!-- Here we render role edit form -->
<div id = 'selected_role' ></div>
<!-- Role edit form ends -->


This is select where User names are displayed, role ID are option value.

In roles.js I have listener where on select role ID is passed for Edit:

(function($) {
$('#user_list').change(function() {
var roleId = $( "#user_list" ).val();
$.ajax({
url: '/common/roles/' + roleId + '/edit',
method: 'GET',
});
});
})(jQuery); /*global jQuery*/


/common/roles/edit.js.erb looks like this:

$("#selected_role").html("<%=j render 'common/roles/editrole', locals: { role: @role } %>");


and it renders role edit partial /common/roles/_editrole.html.erb

<%= form_for :role, method: :patch, remote: true do |f| %>
<form class="m-t" role="form" action="" id="editrole">
<div class="form-group">
<label class="col-sm-2 control-label">General</label>
<div class="col-sm-10" >
<%= f.select :general, Role.generals.to_a.map { |w| [w[0].humanize, w[0]] }, {}, {class:"form-control m-b"} %>
</div>
</div>
<%= f.submit "Save changes", class: "btn btn-primary block full-width m-b" %>
<% end %>
</form>


To complete this form I still need to finish with Update action where I have problem. On submitting role edit form it starts PATCH but with Edit url. Here's error in console:

Started PATCH "/common/roles/1/edit"
ActionController::RoutingError (No route matches [PATCH] "/common/roles/1/edit"):


although particular PATCH route is in place:

common_role PATCH /common/roles/:id(.:format) common/roles#update


In /common/roles_controller.rb I have this:

def update
@role = Role.find(params[:id])
if @role.update_attributes(role_params)
respond_to do |format|
format.html {
flash[:success] = "Role updated!"
redirect_to common_roles_path
}
format.js


In /common/roles/update.js.erb I have this line:
$('.editrole').hide()


I can open form in Edit and untill Update action it works fine.
How do I fix Update action error, please?

Answer

Try this.

<%= form_for role, url: common_role_path(role), method: :patch, remote: true do |f| %>

role here refers to the local variable you passed while rendering the partial.