I've created an app that has several models (say A, B) that are polymorphically associated with a Comment model. When one views a page associated with A controller, show action, comments associated with the A object are displayed as is a form to create a new object. All of this works and is similar to Ryan Bates' 15 minute blog posted on the rails website. However, if I add validation to ensure that the user does not submit a blank comment I'm unsure how to render that. Here's what I have in my Comments controller:
before_filter :load_resources, :only => [:create]
def create
if @comment.save
redirect_to @back
else
render @action
end
end
private
def load_resources
@comment = Comment.new(params[:comment])
case @comment.commentable_type
when 'A'
@a = A.find(params[:a_id]
@comments = @a.comments
@back = a_url(@comment.commentable_id)
@resource = @a
@action = 'as/show'
when 'B'
...
end
end
View partial for comments and form (using Haml):
=render :partial => 'comments/comment', :collection => @comments
%h3 Leave a comment:
-form_for [@resource, Comment.new] do |f|
=f.error_messages
=f.hidden_field :commentable_type, :value => params[:controller].singularize.titleize
=f.hidden_field :commentable_id, :value => params[:id]
=f.hidden_field :editor_id, :value => @current_user.id
=f.hidden_field :creator_id, :value => @current_user.id
%fieldset
=f.label :subject, 'Subject', :class => 'block'
=f.text_field :subject, :class => 'block'
=f.label :text, 'Comment', :class => 'block'
=f.text_area :text, :class => 'block'
.clear_thick
=f.submit 'Submit', :id => 'submit'
What I can seem to figure out is how to deal with validation errors. When validation errors are triggered it doesn't seem to trigger the f.error_messages. Furthermore, when render is triggered it will take the user to a page with the following url: a/2/comments, when I'd like it to render a/2.
newest solution:
def create
subject = ""
if [email protected]
subject = "?subject=#{@comment.subject}"
end
redirect_to @back + subject
end
Then in the A controller show action:
if params.has_key?('subject')
@comment = Comment.create(:subject => params[:subject])
else
@comment = Comment.new
end
This works, but feels kind of ugly...