I figured out the problem with the original post, but I have a new
problem.
When a user submits an invalid comment(if the title or content does not
validate correctly), they get sent back to the article. There are two
problems, though.
1. The form does not keep the previous field content, so the form
resets.
2. All the comments disappear.
Articles controller:
def show
@article = Article.find(params[:id])
@comments = @article.comments.paginate(:page => params[:page])
@title = @article.title
end
Comments controller:
def create
@article = Article.find(params[:article_id])
@comment = @article.comments.build(params[:comment])
@comment.user_id = current_user.id
if @comment.save
flash[:success] = "Comment saved."
redirect_to @article
else
flash[:error] = "Error in creating comment."
render 'articles/show'
end
end
Here's the comment form and the comment display code, if you need it:
Comment Form:
<%= form_for([@article, @article.comments.build]) do |f| %>
<%= render 'shared/error_messages', :object => f.object %>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :content %><br />
<%= f.text_area :content %>
</div>
<div class="actions">
<%= f.submit "Post Comment" %>
</div>
<% end %>
shared/_comments.html.erb:
<% unless @comments.nil? || @comments.empty? %>
<%= render :partial => 'shared/comment', :collection => @comments %>
<%= will_paginate @comments %>
<% end %>
shared/_comment.html.erb
<%= comment.title %><br />
<%= comment.content %><br />
<%= comment.user.name %><br /><br />
Thank you.
--
Posted via http://www.ruby-forum.com/.
--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.
No comments:
Post a Comment