views:

36

answers:

1

I have the following model classes:

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

My upload/show view has a form for to capture a review for the specific upload:

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

When the review validation fails how do I display the error messages in the review form that is part of the upload/show view?

My ReviewController does this:

def create @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

end

Obviously render :action => :new does not work because I need to display the show action of the UploadsController and not the new action of the ReviewsController.

I'm pretty sure there is a simple way to do this, I just can't figure it out!

A: 

Your review controller action should be receiving params['upload_id'] to associate the review with its upload, either through the URL (if reviews are a nested route like POST /uploads/1/reviews), or from a hidden field.

You can use render :template to do your redirection:

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

It's also acceptable to just render the form for the review by itself (i.e. the default 'reviews/new') until the form entry is correct instead of showing the whole page for the upload.

Andrew Vit