我正在尝试使用rails中的remote: true
命令删除帖子。当我不使用ajax时,一切正常。但是当我使用远程true命令时,我得到一个路由错误。
视图:
<% @posts.each do |post| %>
<%= post.title %>
<%= link_to 'delete', post_path(post), method: :delete, data: { confirm: 'Are you sure?' }, remote: true %>
<% end %>
控制器:
def index
@posts = Post.all
end
def destroy
@post = Post.find(params[:id])
@post.destroy
redirect_to :back
end
路线:
resources :posts
这是我在日志中得到的错误。
Started DELETE "/posts" for 127.0.0.1 at 2014-10-11 12:46:33 +0200
ActionController::RoutingError (No route matches [DELETE] "/posts"):
提前致谢。
更新。当我写rake routes
时我得到了这个。
DELETE /posts/:id(.:format) posts#destroy
答案 0 :(得分:0)
要使其发挥作用。
变化:
def destroy
@posts = Post.find(params[:id])
@posts.destroy
redirect_to :back
end
对此:
def destroy
@posts = Post.find(params[:id])
@posts.destroy
respond_to do |format|
format.html { redirect_to posts_url }
format.js { head :no_content }
end
end
和
<%= link_to 'delete', post_path(post), method: :delete, data: { confirm: 'Are you sure?' }, remote: true %>
为:
<%= link_to 'delete', post, method: :delete, data: { confirm: 'Are you sure?' }, remote: true %>
答案 1 :(得分:0)
如果有人遇到任何问题,我设法通过在链接中添加:data => { :type => :json }
来解决此问题。
例如:
<%= link_to "Delete this post", @post, :method => :delete, :remote => true, :data => { :type => :json } %>
我想UJS期待HTML,但是JSON会被返回,所以它会失败并再次发布(我注意到了两个请求)。
希望这有帮助!