Rails form_for在不同控制器中的模型

时间:2010-09-12 04:36:43

标签: ruby-on-rails forms

我有以下模型类:

class Upload < ActiveRecord::Base
   ...
   has_many   :reviews, :order => "created_at DESC"
   ...
end

class Review < ActiveRecord::Base
  ...
  belongs_to :upload
  belongs_to :user
  validates_presence_of :description
  ...
end

我的上传/展示视图有一个表单,用于捕获特定上传的评论:

<% form_for(@review) do |f| %>
  <%= f.error_messages %>
  ...
  <p>
    <%= f.text_area :description, :rows => 5, :cols => 80 %>
  </p>
  ...
  <p>
    <%= f.submit 'Submit Review' %>
  </p>
<% end %>

如果审核验证失败,如何在上传/显示视图中的审核表单中显示错误消息?

我的ReviewController执行此操作:

def创建      @review = current_user.reviews.new(params [:review])

 if @review.save
   flash[:notice] = 'Review was successfully created.'
   redirect_to( @review.upload )
 else
   render :action => :new
 end

显然render :action => :new不起作用,因为我需要显示UploadsController的show动作而不是ReviewController的新动作。

我很确定有一种简单的方法可以做到这一点,我无法理解它!

1 个答案:

答案 0 :(得分:2)

您的审核控制器操作应该接收params['upload_id'],以便通过网址(如果评论是POST /uploads/1/reviews等嵌套路线)或隐藏字段将评论与其上传相关联。

您可以使用render :template进行重定向:

def create
  @review = current_user.reviews.new(params[:review])
  @upload = Upload.find(params['upload_id'])
  @review.upload = @upload
  if @review.save
    flash[:notice] = 'Review was successfully created.'
    redirect_to( @upload )
  else
    flash[:error] = 'Review could not be created.'
    render :template => 'uploads/show'
  end
end

也可以单独呈现评论表单(即默认的'reviews / new'),直到表单输入正确,而不是显示整个页面进行上传。