2012-11-11 25 views
1

問題:試圖實施的 「Like」 功能在我的博客Rails的:使用Ajax

PostIndex:

<% @posts.each do |post| %> 
<tr> 
<td><%= post.name %></td> 
<td><%= link_to post.content, post %></td> 
<td><%= post.created_at.strftime("%Y/%m/%d, %I:%M%p") %></td> 
<td><%= post.view %></td> 
<td><%= post.like %></td> 
<td><%= post.hate %></td> 
<td><%= link_to 'like', like_post_path(post), :remote => true %></td> 
</tr> 
<% end %> 

PostController中:

def like 
@post = Post.find(params[:id]) 
@post.like += 1 
@post.save 

respond_to do |format| 
    format.js 
end 
end 

應用程序/ views/posts/like.js.erb

$('#post').html("<%=j @post.like %>"); 

問:
我相信我沒有正確地我期待在like.js.erb後指指點點。
在索引文件中,簡單地做<%= @ post.view%>工作。但你如何在like.js.erb中做到這一點?

回答

1

當你想Ajax調用後,更新它,你需要在你的HTML文章的像數的一些標識

PostIndex:

<% @posts.each do |post| %> 
    <tr> 
    <td><%= post.name %></td> 
    <td><%= link_to post.content, post %></td> 
    <td><%= post.created_at.strftime("%Y/%m/%d, %I:%M%p") %></td> 
    <td><%= post.view %></td> 
    <td id= "post<%= post.id %>_like"><%= post.like %></td> <!-- set id (identifier) here --> 
    <td><%= post.hate %></td> 
    <td><%= link_to 'like', like_post_path(post), :remote => true %></td> 
    </tr> 
<% end %> 

然後在應用程序/視圖/職位/像.js.erb

<% if @post.errors.blank? %> 
    $("#post<%= @post.id %>_like").html("<%=j @post.like %>"); 
<% end %> 
+0

恐怕這並不能解決上述問題。我不知道爲什麼.. –

+0

我編輯了我的代碼。嘿,請檢查@ post.errors是空白的,如果您在Post模型上添加了一些驗證,驗證不會失敗。 – Santosh

+0

它的工作原理!我假設索引文件中存在拼寫錯誤。謝謝! –

0

使用Ajax的完整法修正了一個錶行:

在你show.html(或index.html)的文件,你可能有一個表已。

<tr> 
<td>row 1</td> 
<td>row 2</td> 
<td>row 3</td> 
</tr> 

讓我們假裝行代表某種變量。那麼上面的表就好像,

<tr> 
<td><%= @variableA %></td> 
<td><%= @variableB %></td> 
<td><%= @variableC %></td> 
</tr> 

我想更改variableA而不重新加載整個頁面。所以我使用Ajax。

我的方法:

def fixvar 
@variableA = 2 
end 

您必須添加一個組件使用Ajax。

def fixvar 
@variableA = 2 
end 

respond_to do |format| 
format.js 
end 

無論你想要什麼,你都會有一個鏈接,通過ajax調用更改。

<%= link_to 'change variable A', URLof_fixvar(@variableA), :remote => true %> 

通過使用選項:remote => true,您在link_to方法中使用了ajax組件。您必須相應地在config/routes.rb中設置URLof_fixvar。 routing

讓我們指定的表進行更新。

<tr> 
<td id="variable_change_<%= @variableA.id %>><%= @variableA %></td> 
<td><%= @variableB %></td> 
<td><%= @variableC %></td> 
</tr> 

我們按照上面的方法來指定我們要更新的行。例如,該行現在被定義爲variable_change_1。 (假設variableA.id爲1)

現在,您需要轉到相關的views文件夾,並創建一個與上面定義的方法相關的.js.erb文件。例如,我有「喜歡」在我的PostController中定義的方法,所以我創建

app/views/posts/like.js.erb 

在這裏,你只需要一行代碼:

$("#variable_change_<%= @variable.id %>").html("<%= @variableA %>"); 

的.html前第一部分是指向在指定的行,後面的部分是我們想要更新的值。完成!