2013-03-22 48 views
0

我傳遞集合(@feed_items)經由局部一個_feed_item更新爲=>:dailypost。Like按鈕不與AJAX

裏面的_feed_item部分我渲染另一部分爲_like_button,我用:當地人繼續使用dailypost。

一切都正常工作與數據庫。喜歡加入和取出:)但

我想用(AJAX)create.js.erb & destroy.js.erb像按鈕。 由於某些原因,只有最上面的帖子得到正確更新,我必須刷新頁面才能看到它下面的那個。

我知道的解決方案涉及分配一個唯一的帖子ID每一個「喜歡」的元素,說:「像-123」,但是這是我在哪裏卡住了.......

我也知道該問題可能在_feed_items.html.erb中,因爲我傳遞了兩個ID ....任何建議?

查看

_feed.html.erb

<% if @feed_items.any? %> 
    <ol> 
    <%= render partial: 'shared/feed_item', collection: @feed_items, :as => :dailypost %> 
    </ol> 
<% end %> 

_feed_items.html.erb

<li id="<%= @dailypost.id %>"> 

    <span class="user"> 
    <%= link_to dailypost.user.name, dailypost.user %> 
    <span class="content"><%= dailypost.content_html %></span> 

    <div id="like"> 
    <%= render :partial => 'likes/like_button', :locals =>{:dailypost => dailypost} %> 
    </div> 

</li> 

_like_button.html.erb

<% if like = current_user.likes.find_by_dailypost_id(dailypost.id) %> 
<%= form_for like, :html => { :method => :delete }, :remote => true do |f| %> 
    <%= f.submit "Unlike" %> 
<% end %> 
<% else %> 
<%= form_for current_user.likes.build, :remote => true do |f| %> 
    <div><%= f.hidden_field :dailypost_id, value: dailypost.id %></div> 
    <%= f.hidden_field :user_id %> 
    <%= f.submit "Like" %> 
<% end %> 
<% end %> 

create.js.erb

$("#like").html("<%= escape_javascript(render :partial => 'like_button', :locals => {:dailypost => @dailypost}) %>"); 

destroy.js.erb

$("#like").html("<%= escape_javascript(render :partial => 'like_button', :locals => {:dailypost => @dailypost}) %>"); 

控制器

class LikesController < ApplicationController 


    respond_to :html, :js 

    def create 
    @like = Like.create(params[:like]) 
    @dailypost = @like.dailypost 
    respond_to do |format| 
     format.js 
     format.html { redirect_to :back } 
    end 
    end 

    def destroy 
    like = Like.find(params[:id]).destroy 
    @dailypost = like.dailypost 
    respond_to do |format| 
     format.js 
     format.html { redirect_to :back } 
    end 
    end 

end 

回答

1

Hmmm.Replace一線在_feed_items.html.erb與此。

<li id="dailypost<%= dailypost.id %>"> 

,並在create.js.erb和destroy.js.erb,更改

$("#like").html(...) 

$("#dailypost<%= dailypost.id%> #like").html(...) 

這應該工作。

+0

我已經更新了我的問題上面.... @Abibullah Rahamathulah – 2013-03-22 07:59:24

+0

哎呀控制器。我想應該是在@ create.js.erv – 2013-03-22 08:21:33

+0

dailypost.id所以我改變了create.js.erb這個$( 「#dailypost <%= @ dailypost.id%> #like」)。HTML(.. ),它在終端中工作,但它不會呈現不同按鈕。我必須刷新頁面才能看到更改... @ Abibullah Rahamathulah – 2013-03-22 08:31:00