In my Review model, I have the following:
class Review < ActiveRecord::Base
belongs_to :vendor
belongs_to :user
has_many :votes
validates_presence_of :summary
end
I submit a new entry as follows in the URL:
vendors/9/reviews/new
The new.html.erb contains a form as follows:
<%= error_messages_for 'review' %>
<h1>New review for <%= link_to @vendor.name, @vendor%></h1>
<% form_for(@review, :url =>vendor_reviews_path(@vendor.id)) do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :summary %><br />
<%= f.text_area :summary, :rows=>'3', :class=>'input_summary' %>
<%= f.hidden_field :vendor_id, :value => @vendor.id %>
</p>
<p>
<%= f.submit 'Submit Review' %>
</p>
<% end %>
When I leave the field for :summary blank, I get an error, not a validation message:
You have a nil object when you didn't expect it! The error occurred while evaluating nil.name
Extracted source (around line #3):
1: <%= error_messages_for 'review' %>
2:
3: <h1>New review for <%= link_to @vendor.name, @vendor%></h1>
I don't understand what is happening, it works if :summary is populated
def new
@review = Review.new
@vendor = Vendor.find(params[:vendor_id])
@review = @vendor.reviews.build
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @review }
end
end
def create
@review = Review.new(params[:review])
#@vendor = Vendor.find(params[:vendor_id]) #instantiate the vendor from the URL id -- NOT WOKRING
#@review = @vendor.reviews.build #build a review with vendor_id -- NOT working
@review = @current_user.reviews.build params[:review]#build a review with the current_user id
respond_to do |format|
if @review.save
flash[:notice] = 'Review was successfully created.'
format.html { redirect_to review_path(@review) }
format.xml { render :xml => @review, :status => :created, :location => @review }
else
format.html { redirect_to new_review_path(@review) }
format.xml { render :xml => @review.errors, :status => :unprocessable_entity }
end
end
end
My guess is that when it fails it is going to redirect_to new_review_path(@review)
and so doesn't know the vendor it. How can I redirect to vendor/:vendor_id/reviews/new
instead?