我按照教程创建了博客应用程序。所以我有帖子和评论。帖子表单中字段的验证工作完美。一篇文章评论部分的验证也有效,但我无法将错误打印出来。
评论模型:
class Comment belongs_to :post validates :commenter, :presence => true end
评论控制器:
def create @post = Post.find(params[:post_id]) @comment = @post.comments.build(params[:comment]) if @comment.save redirect_to post_path(@post) else render :template => 'posts/show' end end def destroy @post = Post.find(params[:post_id]) @comment = @post.comments.find(params[:id]) @comment.destroy render :template => 'posts/show' end
邮政控制人:
def index @posts = Post.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @posts } end end def show @post = Post.find(params[:id]) @comment = @post.comments.build #added #@comment = @Comment.new #added respond_to do |format| format.html # show.html.erb format.xml { render :xml => @post } end end def new @post = Post.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @post } end end def edit @post = Post.find(params[:id]) end def create @post = Post.new(params[:post]) respond_to do |format| if @post.save format.html { redirect_to(@post, :notice => 'Post was successfully created.') } format.xml { render :xml => @post, :status => :created, :location => @post } else format.html { render :action => "new" } format.xml { render :xml => @post.errors, :status => :unprocessable_entity } end end end def update @post = Post.find(params[:id]) respond_to do |format| if @post.update_attributes(params[:post]) format.html { redirect_to(@post, :notice => 'Post was successfully updated.') } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @post.errors, :status => :unprocessable_entity } end end end def destroy @post = Post.find(params[:id]) @post.destroy respond_to do |format| format.html { redirect_to(posts_url) } format.xml { head :ok } end end
我用的形式是:
<%= form_for([@post, @post.comments.build]) do |f| %>
我如何获得评论的.errors?如果我尝试我总是得到:未定义的方法`errors'或nil对象。
请帮助,我对rails来说是全新的。
谢谢!
Picki
答案 0 :(得分:4)
问题是,每次加载表单时,您都在构建新的注释。像这样,带有验证错误的注释永远不会进入您的表单。
在控制器中创建注释,类似于此 - 详细信息取决于您的应用程序:
# posts controller
def show
@post = Post.find(params[:id])
@comment = Comment.new
end
# comments controller
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.build(params[:comment])
if @comment.save
redirect_to @post
else
render :new
end
end
改变你的形式:
<%= form_for([@post, @comment]) do |f| %>