davideghz
davideghz

Reputation: 3685

Rails - delete li element with Ajax

I've a users list and I want to delete elements on click of a "delete" link on the same line.

Views:

# users/index.html.erb
<ul class="users">
  <%= render @users %>
</ul>

# users/_user.html.erb
<li id="user-<%= user.id %>">
  <%= link_to user.email, user %>
  <% if current_user.admin? %>
      <%= link_to "delete", user, remote: true, method: :delete, data: { confirm: "You sure?" } %>
  <% end %>
</li>

Users Controller:

# users_controller.rb
def destroy
  User.find(params[:id]).destroy
  flash[:success] = "User deleted"
  respond_to do |format|
    format.html { redirect_to users_url }
    format.js
  end
end

The javascript to delete the list element is:

# users/destroy.js.erb
$("li#<%= user.id %>").remove();

On click nothing happen, but on page refresh the resource is correctly destroyed. Checking server's LOG I see the following error:

Completed 500 Internal Server Error in 40ms (ActiveRecord: 5.0ms)

ActionView::Template::Error (undefined local variable or method user' for #<#<Class:0x0000000851d300>:0x00000008e8e7e0>): 1: $("li#<%= user.id %>").remove(); app/views/users/destroy.js.erb:1:in _app_views_users_destroy_js_erb___2066095411338793994_74738360'
app/controllers/users_controller.rb:46:in `destroy'

Can you pls help me to understand where the error is and why 'user' is undefined? Thanks

edit

I know there are many q&a similar to this question, and I actually build my code consulting these questions. Still, I'm stuck and I need support. Pls do not mark the question as duplicate.

Upvotes: 0

Views: 1811

Answers (2)

Kirka121
Kirka121

Reputation: 505

your destroy.js.erb template is not getting the user variable, as it is undefined. try:

def destroy
 @user = User.find(params[:id])
 @user.destroy

 respond_to do |format|
  format.html { redirect_to users_url }
  format.js
 end
end

and

$("li#<%= @user.id %>").remove();

the reason this works is because rails passes data from controller to view by setting variables with @ prefix. so you set @user to an instance of the model you grabbed from the database, then you called .destroy on that model, and it got deleted, and then you rendered your destroy.js template which had @user in it as well, and you deleted the list item matching the 'li#233' selector or whatever the id integer was

Upvotes: 2

You're not defining an user variable.

You would save your @user_id in a variable to be accessible in your js.erb. Like that:

def destroy
  @user_id = params[:id]  
  ...
end

And then:

$("li#<%= @user_id %>").remove();

Upvotes: 0

Related Questions