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

时间:2012-01-15 13:54:37

标签: ruby-on-rails controller models

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

模特邮报:

#/models/post.rb 
class Post < ActiveRecord::Base
   has_many :comments
   validates :title, :content, :presence => true
end

模特评论:

#/models/comment.rb
class Comment < ActiveRecord::Base
   belongs_to :post
   validates :name, :comment, :presence => true
end

评论控制器

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

查看评论表:

/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 %>

/views/posts/show.html.erb

<%= render 'comments/form' %>

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

提前致谢。

3 个答案:

答案 0 :(得分:5)

render "posts/show"代替redirect_to post_path(@post)放入CommentsController

答案 1 :(得分:2)

答案 2 :(得分:1)

如果评论无效,则不应重定向到post_path(@post)

class CommentsController < ApplicationController
  def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.new(params[:comment])

    if @comment.save
      redirect_to post_path(@post), notice: 'Comment was successfully created.'
    else
      render action: "posts/show", error: 'The comment you typed was invalid.'
    end
  end
end

并更改/views/comments/_form.html.erb中的第一个表单行:

<%= form_for([@post, @post.comments.build]) do |f| %>

为:

<%= form_for([@post, (@comment || @post.comments.build)]) do |f| %>

然后,当它无法保存时,您应该看到错误消息。