この質問は、モデルの作成/編集機能をそのインデックス ページに移動することを扱う、昨日尋ねた以前の質問に便乗するものです。私が抱えている最後の問題の1つは、モデルを削除するときに、モデルのリストをリロードしてデータベースの変更を反映するJavaScriptを実行することです。この js は html としてレンダリングされています。関連すると思われるコードは次のとおりです。
私のコントローラーで:
def destroy
@post = Post.find(params[:id])
@post.destroy
flash[:notice] = "Successfully destroyed post."
@posts = Post.all
respond_to do |format|
format.js {render :content_type => 'text/javascript' }
end
end
部分的な投稿のリスト(私が参照している破棄リンクがあります):
<table>
<tr>
<th>Title</th>
<th>Content</th>
</tr>
<% for post in @posts %>
<tr>
<td><%= post.title %></td>
<td><%= post.content %></td>
<td><%= link_to "Edit", edit_post_path(post), :class => "edit" %></td>
<!--
This is the problem here... I can't seem to get it to work.
It DOES delete the record, but then gets redirected to /posts/:id
and displays my javascript as html.
-->
<td><%= link_to "Destroy", post , :confirm => 'Are you sure?', :method => :delete, :class => 'destroy' %></td>
</tr>
<% end %>
</table>
destroy.js.erb:
$("#post_errors").hide(300);
$("#flash_notice").html("<%= escape_javascript(flash[:notice])%>");
$("#flash_notice").show(300);
$("#posts_list").html("<%= escape_javascript( render(:partial => "posts") ) %>");
ページの読み込み時に読み込まれる JavaScript:
// Setting up the ajax requests for the forms/links.
$(document).ready(function() {
$("#new_post").submitWithAjax();
$("a.edit").each(function(){
$(this).getWithAjax();
});
$("a.destroy").each(function(){
$(this).postWithAjax();
});
});
// Setting up ajax for sending javascript requests
jQuery.ajaxSetup({
'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
});
jQuery.fn.submitWithAjax = function() {
this.submit(function() {
$.post(this.action, $(this).serialize(), null, "script");
return false;
});
return this;
};
jQuery.fn.getWithAjax = function() {
this.click(function() {
$.get(this.href, null, null, "script");
return false;
});
return this;
};
jQuery.fn.postWithAjax = function() {
this.click(function() {
$.post(this.href, null, null, "script");
return false;
});
return this;
};
私が使用しているすべてのコードを確認するには、私が投稿した他の質問をチェックしてください。また、Chrome を実行しているときに破棄リンクをクリックすると、Chrome から JavaScript の警告が表示されます。
Resource interpreted as document but transferred with MIME type text/javascript.