我在我的Rails应用程序中使用gem“acts_as_votable”,以便用户可以对帖子进行投票。
我正在添加Ajax功能,以便在用户提交帖子时不必刷新整个页面。这就是我所拥有的:
的routes.rb
Rails.application.routes.draw do
devise_for :users, controllers: {registrations: 'registrations'}
resources :posts do
member do
put "like", to: "posts#upvote"
put "dislike", to: "posts#downvote"
end
end
# Define Root URL
root 'pages#index'
# Define Routes for Pages
get '/home' => 'pages#home'
get '/explore' => 'pages#explore'
get '/privacy' => 'pages#privacy'
get '/:id' => 'pages#profile'
end
pages_controller.rb
def explore
@posts = Post.where('created_at >= :one_days_ago', one_days_ago: Time.now - 16.hours)
end
posts_controller.rb
class PostsController < ApplicationController
def index
@posts = Post.allow
end
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
@post.user_id = current_user.id
respond_to do |f|
if (@post.save)
f.html { redirect_to :back, :flash => { :notice => "Posted" } }
else
f.html { redirect_to :back, :flash => { :alert => "Error" } }
end
end
end
def destroy
@post = Post.find(params[:id])
if current_user == @post.user
@post.destroy
end
redirect_to :back, alert: 'Deleted.'
end
def upvote
@posts = Post.find(params[:id])
@posts.upvote_by current_user
respond_to do |format|
format.html { redirect_to :back }
format.js
end
end
def downvote
@posts = Post.find(params[:id])
@posts.downvote_by current_user
respond_to do |format|
format.html { redirect_to :back }
format.js
end
end
private
def post_params # allows certain data to be passed via form.
params.require(:post).permit(:user_id, :content)
end
end
explore.html.erb
<% if @posts.each do |p| %>
<div class="panel-body">
<p class="post-content"><%= auto_link(p.content, :html => { :target => '_blank' }) %></p>
<%= render :partial => 'vote', :class => "vote", :locals => { p: @posts } %>
</div>
<% end %>
_vote.html.erb
<div id="vote_<%= p.id %>" class="vote">
<%= link_to 'Vote Up', like_post_path(p), :class => "upvote", :method => :put, :remote => true %>
<span><%= p.score %></span> <!--show the current vote-->
<%= link_to 'Vote Down', dislike_post_path(p), :class => "downvote", :method => :put, :remote => true %>
</div>
upvote.js.erb
$(document).ready(function(){
$('#vote_<%= p.id %>').html("<%= escape_javascript render :partial => '/pages/vote' %>");
});
当我去运行项目时,我收到了这个错误:
NoMethodError in Pages#explore
Showing /home/ubuntu/workspace/app/views/pages/_vote.html.erb where line #1 raised:
undefined method `id' for #<Post::ActiveRecord_Relation:0x007f6715d018e8>
Did you mean? ids
<div id="vote_<%= p.id %>" class="vote">
问题源于尝试渲染_votes.html.erb。
我在哪里错了?我已经坚持了一段时间,并希望得到任何帮助。谢谢!
答案 0 :(得分:0)
您正在将整个集合传递给部分
<% if @posts.each do |p| %>
<div class="panel-body">
<p class="post-content"><%= auto_link(p.content, :html => { :target => '_blank' }) %></p>
<%= render :partial => 'vote', :class => "vote", :locals => { p: @posts } %>
</div>
<% end %>
在<%= render :partial => 'vote', :class => "vote", :locals => { p: @posts } %>
行中,将@posts
替换为p