将变量从控制器传递到视图

Mik*_*ike 9 controller ruby-on-rails models

我在rails上做了一个简单的博客.我有一个Post模型和一个Comment模型.当您创建评论时,如果评论无效,我想显示错误.我该怎么办?

模特邮报:

#/models/post.rb 
class Post < ActiveRecord::Base
   has_many :comments
   validates :title, :content, :presence => true
end
Run Code Online (Sandbox Code Playgroud)

型号评论:

#/models/comment.rb
class Comment < ActiveRecord::Base
   belongs_to :post
   validates :name, :comment, :presence => true
end
Run Code Online (Sandbox Code Playgroud)

评论控制器

class CommentsController < ApplicationController
  def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.create(params[:comment])
    redirect_to post_path(@post)
  end
end
Run Code Online (Sandbox Code Playgroud)

查看评论表:

/views/comments/_form.html.erb

<%= form_for([@post, @post.comments.build]) do |f| %>
  <% if @comment.errors.any?  %>
     error! 
  <% end %>
  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :comment %><br />
    <%= f.text_area :comment %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
Run Code Online (Sandbox Code Playgroud)

/views/posts/show.html.erb

<%= render 'comments/form' %>
Run Code Online (Sandbox Code Playgroud)

如何从控制器CommentController传递@comment来查看/post/show.html.erb?

提前致谢.

shi*_*ime 5

render "posts/show",而不是redirect_to post_path(@post)在你的CommentsController.