我正在使用投票构建应用程序(帖子有很多票,用户有很多票)。当我没有限制每个用户的投票数时,它正在工作,但在添加验证后,当我尝试对同一用户之前投票的帖子进行投票时,会出现以下错误:
>undefined method `model_name' for NilClass:Class
>Extracted source (around line #28):
>25: <% end %>
>26:
>27: <table class="posts" summary="User posts">
>28: <%= render @posts %>
>29: </table>
>Trace:
>app/views/posts/index.html.erb:28:in `_app_views_posts_index_html_erb__978098650233580665_2485618500'
>app/controllers/votes_controller.rb:23:in `create'
投票给用户之前未投票的帖子时有效。当用户已经投票支持该帖子,然后重定向没有错误时,如何使用rails来刷新错误?我敢肯定我错过了一些明显的东西。当我尝试通过rails控制台添加投票时验证工作(即,如果该用户已经投票,则rails不会将新投票添加到数据库)。谢谢 -
vote.rb中的相关代码:
class Vote < ActiveRecord::Base
attr_accessible :user_id, :post_id
validate :only_one_user_per_post
belongs_to :user
belongs_to :post, :counter_cache => true
private
def only_one_user_per_post
if Vote.where("user_id = ? AND post_id = ?", self.user_id, self.post_id).all.any?
errors.add(:user_id, "Can only post once per post!")
end
end
end
来自VotesController.rb的创建
def create
@vote = Vote.new(params[:vote])
post = params[:vote][:post_id]
uid = params[:vote][:user_id]
if @vote.save
flash[:success] = "You voted for the article"
redirect_to root_path
else
flash[:failure] = "You did not vote"
render 'posts/index'
end
index.html.erb中的相关代码:
<% flash.each do |key, value| %>
<div class="flash <%= key %>"><%= value %></div>
<% end %>
<table class="posts" summary="User posts">
<%= render @posts %>
</table>
以下是_post.html.erb的相关摘录:
<%= form_for @vote do |f| %>
<div class="right"> <%= image_submit_tag "plus32.png", :size => "16x16", :class => "squareicon" %>
<span class="label success"><%= post.votes_count %></span>
</div>
答案 0 :(得分:3)
在你的控制器中,在else-branch中你有以下代码:
else
flash[:failure] = "You did not vote"
render 'posts/index'
end
您还需要检索@posts
以缓解错误。或者改为使用redirect_to posts_path
。
希望这有帮助。