【发布时间】:2014-10-15 17:44:16
【问题描述】:
我的 cmets 资源嵌套在我的帖子资源中,并且这两个资源都是 act_as_votable。
我将如何定义赞成/反对票?这是我现在的做法(cmets 控制器):
def upvote
@post = Post.find(params[:id])
@comment = @post.comment.find(params[:post_id])
@post.upvote_by current_user
redirect_to posts_path
end
def downvote
@post = Post.find(params[:id])
@comment = @post.comment.find(params[:post_id])
@post.downvote_by current_user
redirect_to posts_path
end
这是新的并创建动作和参数:
def new
@post = Post.find(params[:post_id])
@comment = Comment.new(params[:id])
end
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(comment_params)
@comment.post_id = @post.id
if @comment.save
redirect_to @post
else
redirect_to new_post_comment_path(post)
end
end
private
def comment_params
params.require(:comment).permit(:body, :post_id)
结束
这是我收到的错误消息:
No route matches {:action=>"upvote", :controller=>"comment", :format=>nil, :id=>nil,
:post_id=>#<Comment id: 22, body: "test", user_id: 1, post_id: 4, created_at:
"2014-10-14 07:28:22", updated_at: "2014-10-14 07:28:22", cached_votes_total: 0,
cached_votes_score: 0, cached_votes_up: 0, cached_votes_down: 0,
cached_weighted_score: 0, cached_weighted_total: 0, cached_weighted_average: 0.0>}
missing required keys: [:id]
我的嵌套路线:
resources :posts do
member do
put "like", to: "posts#upvote"
put "dislike", to: "posts#downvote"
end
resources :comments do
member do
get 'upvote' => 'comment#upvote', as: :upvote
get 'downvote' => 'comment#downvote', as: :downvote
end
end
end
cmets/index.html.erb:
<div class="comments">
<% @comments.each do |comment| %>
<p><%= comment.body %></p>
<div>
<%= link_to "up", upvote_post_comment_path(comment) %>
<%= link_to "down", downvote_post_comment_path(comment) %>
<%= comment.score %>
</div>
<% end %>
</div>
【问题讨论】:
-
欢迎来到 SO!我在这里看到两个问题。首先,一个设计问题:upvote 和 downvote 动作应该在哪里进行,即。它们应该是 cmets 控制器中的非资源性操作吗?二、路由问题:如何为新动作添加路由?您希望我们关注哪个问题? :)
-
路由问题、错误信息以及我的非资源操作是否设置正确。
-
路由文件的相关部分是什么样的?
-
添加了相关路由。
标签: ruby-on-rails ruby ruby-on-rails-4