当我点击upvote时出现错误 enter image description here
继承我的routes.rb
Rails.application.routes.draw do
#root 'pages#index'
resources :posts
devise_for :users
# Define root URL
root 'pages#index'
# Define roots for pages
get '/home' => 'pages#home'
get '/user/:id' => 'pages#profile'
get '/explore' => 'pages#explore'
resources :posts do
member do
put "like", to: "posts#upvote" # maybe change it to POSTS??
put "dislike", to: "posts#downvote" # maybe change it to POSTS??
end
end
我的posts_controller.rb
class PostsController < ApplicationController
#resources posts
def new
@post = current_user.posts.build
end
def index
@post = Post.all
end
def show
@post = Post.find(params[:id])
end
def create
@user = User.find(session[:user_id])
@post = current_user.posts.build(permit_post)
if @post.save
flash[:success] = "Uploaded"
redirect_to '/'
else
flash[:error] = @posts_errors_full_messages
end
end
def upvote
current_user = User.find_by_id(session[:user_id])
@post = Post.find(params[:id])
current_user.upvotes @post
redirect_to :back
end
def downvote
@post = Post.find(params[:id])
@post.downvote_by current_user
redirect_to :back
end
private
def permit_post
params.require(:post).permit(:image, :title);
end
end
我的索引
<%= link_to like_post_path(@post), method: :put, class: 'upvote' do %>
在URL中显示myurl.com/posts/%23/like 我认为这意味着它没有获得ID,我该如何解决? 事先感谢,这让我筋疲力尽
编辑: 我用@x替换@post,因为我使用了一个循环,修复了网址,但仍然遇到了同样的错误,即无法找到没有ID的帖子。
答案 0 :(得分:0)
如果你传递帖子的ID,因为喜欢是帖子的成员(孩子),链接应该看起来像/ posts / 41 / like
接下来,你应该删除.exists?部分来自控制器。那种东西只属于模型。
您的控制器看起来应该更像:
def upvote
# current_user = User.find_by_id(session[:user_id]) -- since you use devise, you don't need this
@post = Post.find(params[:id])
current_user.upvotes @post
redirect_to :back
end
您的观看链接
<%= link_to like_post_path(@post), method: :put, class: 'upvote' do %>
您正在关注教程吗? Rails 4中不建议使用find_by_id。您是创建自己的身份验证还是使用gem?
在引用集合时使用单数名称并不是rails约定(因此我假设您之前与@post的链接)。因此,如果您尝试在帖子索引页面上投票,那么您的帖子控制器应该是
def index
@posts = Post.all
end
您的视图循环将是
<%= @posts.each do |post|
<!-- Other view code here for what you want to display >
<%= link_to like_post_path(post), method: :put, class: 'upvote' do %>
<% end %>