我的代码在概念上与迈克尔·哈特尔的铁路教程非常相似 - 以下用户部分,但它与提出这个问题的方式不同。
所有细节之前的问题:
当我从_like中删除remote: true
时,一切顺利,
当_like.html.erb有remote: true
时,我得到了:
No route matches {:action=>"destroy", :controller=>"likes", :artwork_id=>1} missing required keys: [:id]
我不明白为什么。
代码片段:
的观点/艺术品
show.html.erb:
<div id="like_link">
<% if @artwork.liked_users.include?(current_user) then %>
<%= render 'unlike' %>
<% else %>
<%= render 'like' %>
<% end%>
</div>
_unlike.html.erb:
<%= link_to 'UNLike', like_path(artwork_id: @artwork.id), method: :delete, remote: true %>
_like.html.erb:
<%= link_to 'Like', likes_path(artwork_id: @artwork.id), method: :post, remote: true %>
的观点/喜欢
create.js.erb:
$("#like_link").html("<%= escape_javascript(render("artworks/unlike")) %>")
$("#likes").html('<%= @artwork.likes_count %>')
destroy.js.erb:
$("#like_link").html("<%= escape_javascript(render("artworks/like")) %>")
$("#likes").html('<%= @artwork.likes_count %>')
和喜欢的控制器 - controllers / likes_controller.rb
class LikesController < ApplicationController
respond_to :html, :js
def create
@artwork = Artwork.find(params[:artwork_id])
current_user.like!(@artwork)
respond_with @artwork
end
def destroy
@artwork = Artwork.find(params[:artwork_id])
current_user.unlike!(@artwork)
respond_with @artwork
end
end
的routes.rb:
resources :artworks
resources :likes, only: [:create, :destroy]
答案 0 :(得分:1)
在这里创建
的路线resources :likes, only: [:create, :destroy]
根据RAILS惯例,它为那些use :id
的受众控制器创建路由,例如"likes/:id"
而不是likes/artwork_id
,所以请手动创建喜欢路线或遵循惯例。
答案 1 :(得分:0)
这是有问题的一行:
# _like.html.erb
<%= link_to 'Like', likes_path(artwork_id: @artwork.id), method: :post, remote: true %>
这里的问题是likes_path(artwork_id: @artwork.id), method: :post
。如果您检查rake routes
的输出,则应该看到likes
资源的以下两行:
likes POST /likes(.:format) likes#create
like DELETE /likes/:id(.:format) likes#destroy
正如您所看到的,likes_path
不会接受除格式之外的参数,因此您的likes_path(artwork_id: @artwork.id)
无法映射到任何路径。
您应该使用以下内容更新路线定义:
# app/config/routes.rb
resources :artworks do
resources :likes, only: [:create, :destroy]
end
通过此路线定义,您的link_to
来电将是:
# _like.html.erb
<%= link_to 'Like', artwork_likes_path(artwork_id: @artwork.id), method: :post, remote: true %>
# _unlike.html.erb
# Replace this_like_id with like_id attribute for this like being destroyed.
<%= link_to 'UNLike', artwork_likes_path(artwork_id: @artwork.id, id: this_like_id), method: :delete, remote: true %>
答案 2 :(得分:0)
你不必传递艺术品
<%= link_to 'Like', likes_path(@artwork), method: :post, remote: true %>
<%= link_to 'UNLike', like_path(@artwork), method: :delete, remote: true %>
现在您可以通过
在控制器中访问它params[:id]