Removing Posts Using Ajax in Rails

I have a user page where the user can enter and send messages. I use Ajax to allow the user to do this from the user / show page. The problem I am encountering occurs when I try to allow users to delete messages. When the user clicks the delete link, the message is deleted from the page. However, when I reload the page, the message is returned. It does not collapse.

I have the same code implemented on the user / edit page in a different context, and this works fine, because the post after is destroyed when the form is submitted. However, in this situation, when there is no form, I am not sure how to do it.

Here is my setup:

:user has_many :posts
:post belongs_to :user
:post belongs_to :post_type
:post_type has_many :posts

User # show:
This is the code for the user who should send the message. It works great.

<% if logged_in? && current_user == @user %>
  <% form_tag(:controller => "posts", :action => "create") do %>
    <div><%= text_area_tag(:message, nil, :size => "27x3") %></div>
    <div><%= submit_tag("Post") %></div>
    <div><%= label_tag(:post_type_id, "Update type?", :class => 'typeLabel') %></div>
    <div><%= collection_select(@posts, :post_type_id, PostType.all, :id, :name) %></div>
  <% end %>
<% end %>

This is the code where the messages are displayed, including the "delete link":

<% @user.posts.each do |c| %>
  <div class="postS">
    <div><%=h c.message %></div>
    <p><%=h c.post_type.name %></p>
    <p>Posted <%=h time_ago_in_words(c.created_at) %> ago</p>       
    <% if logged_in? && current_user == @user %>
        <%= link_to_function "- Delete Post", "if(confirm('Are you sure you want to permanently delete this post?')) $(this).up('.postS').remove()" %>                          
    <% end %>                   
<%end%>

PostsController

def destroy
  @post = Post.find(params[:id])
  if @post.destroy
    redirect_to :back
  else
    flash[:notice] = "Post failed to delete."
    redirect_to :back
end
end

Let me know if any other information is helpful. Thanks!

Update 2

I tried using link_to_remoteas described in the answer below. I agree that this is the right decision, but cannot make it work. I think this is due to a route problem.

I have messages configured as a user resource, for example:

map.resources :users, :member => { :enable => :put } do |users|
  users.resources :posts
end  

When I implement the code link_to_remoteindicated in the answer, I get a "no method error" exception as follows: undefined methodpost_url 'for # `

, , . ? , ?

UPDATE

Rails Guides . .

, , :

<%= link_to_remote "- Delete Post", :url => { :controller => 'posts', :action => 'destroy', :id => @user.posts, :method => :delete }, :confirm => "Are you sure you want to permanetly delete this post?", :success => "$(this).up('.postS').remove();" %>  

, "", . , , . , . , , . , , ajax .

. , :: id = > @user.posts

, . , :
PostsController # destroy ( 127.0.0.1 2009-12-17 02:07:05) [POST]

`Parameters: {"action"=>"destroy", "authenticity_token"=>"GZfPHUc2+qPa6Fj5jNogMyhuB4YUO+KlOdkwjM5NSvw=", "id"=>"12/11", "method"=>"delete", "controller"=>"posts"}  `

id = > "12/11". , .

paramater : id = > @user.post, " ". undefined `post ' #User: 0x3ddc20c

:id => user_post_url(@user, @post), : "user_post_url [, ].

:id => user_posts_url(@user, @posts), . , . . , .

, . ?

3

:

    user_posts GET    /users/:user_id/posts(.:format)          {:controller=>"posts", :action=>"index"}
               POST   /users/:user_id/posts(.:format)          {:controller=>"posts", :action=>"create"}
 new_user_post GET    /users/:user_id/posts/new(.:format)      {:controller=>"posts", :action=>"new"}
edit_user_post GET    /users/:user_id/posts/:id/edit(.:format) {:controller=>"posts", :action=>"edit"}
     user_post GET    /users/:user_id/posts/:id(.:format)      {:controller=>"posts", :action=>"show"}
               PUT    /users/:user_id/posts/:id(.:format)      {:controller=>"posts", :action=>"update"}
               DELETE /users/:user_id/posts/:id(.:format)      {:controller=>"posts", :action=>"destroy"}

4

ScottD, :

<%= link_to_remote "- Delete Post", :url => user_post_url(@user,c), :method => :delete, :confirm => "Are you sure you want to permanently delete this post?", :success => "$(this).up('.postS').remove();" %>  

, javascript remove - . , delete. , . , . , , :: success = > "$ (this).up('. PostS'). Remove();"

, , :

Processing PostsController#destroy (for 127.0.0.1 at 2009-12-17 11:59:18) [DELETE]  
  Parameters: {"action"=>"destroy", "authenticity_token"=>"ccF1QNCGs9IlvbIYWwmQmcbi7kROgQsTZjM1dM687xA=", "_method"=>"delete", "id"=>"14", "controller"=>"posts", "user_id"=>"1"}  
  User Columns (3.2ms)   SHOW FIELDS FROM `users`
  User Load (29.6ms)   SELECT * FROM `users` WHERE (`users`.`id` = 1) ORDER BY name
  Post Columns (8.7ms)   SHOW FIELDS FROM `posts`
  Post Load (1.6ms)   SELECT * FROM `posts` WHERE (`posts`.`id` = 14) 
    app/controllers/posts_controller.rb:22:in `destroy'
  SQL (0.1ms)   BEGIN
    app/controllers/posts_controller.rb:23:in `destroy'
  Post Destroy (0.5ms)   DELETE FROM `posts` WHERE `id` = 14
    app/controllers/posts_controller.rb:23:in `destroy'
  SQL (0.9ms)   COMMIT
    app/controllers/posts_controller.rb:23:in `destroy'
Redirected to http://localhost:3000/users/1
Completed in 65ms (DB: 45) | 302 Found [http://localhost/users/1/posts/14]  

. , javascript .

, , , ( ). , javascript ?

# 5

, html link_to_remote, :

<a href="#" onclick="if (confirm('Are you sure you want to permanently delete this post?')) { new Ajax.Request('http://localhost:3000/users/1/posts/18', {asynchronous:true, evalScripts:true, method:'delete', onComplete:function(request){$(this).up('.postS').remove();}, parameters:'authenticity_token=' + encodeURIComponent('ccF1QNCGs9IlvbIYWwmQmcbi7kROgQsTZjM1dM687xA=')}); }; return false;">- Delete Post</a>  

, Firebug , "" :

POST http://localhost:3000/users/1/posts/18  302 Moved Temporarily  
GET  http://localhost:3000/users/1 200 OK
+5
2

, link_to_function, Javascript, POST . Ajax try link_to_remote. AJAX, javascript , :success :complete.

, :

<% if logged_in? && current_user == @user %>
  <%= link_to_remote "- Delete Post", :url => user_post_url(@user,c, :format => :json), :method => :delete  , :confirm => "Are you sure you want to permanetly delete this post?", :success => "$(this).up('.postS').remove();" %>                                                      
<% end %> 

Rails API docs link_to_remote.

Post Controller, Ajax. json gem json.

def destroy
  @post = Post.find(params[:id])
  respond_to do |format|
    if @post.destroy
      format.html { redirect_to :back }
      format.json { :success => true }.as_json
    else
      flash[:notice] = "Post failed to delete."
      format.html { redirect_to :back }
      format.json { :success => false }.as_json
    end
  end
end

, , .

+6

, , , , ,

:success => "$(this).up('.postS').remove();"

link_to_remote , . - div DOM.

, , .

0

All Articles