I want to ask if what I have done is a good practice.
I have two models: a discussion has many posts.
In my discussions#show all posts are displayed. Now I want to add a form, so I can create a new post at that discussion.
discussions_controller.rb show()
@discussion = Discussion.find(params[:id])
@post = @discussion.posts.build
show.html.erb
<%= render :partial => 'posts/form' %>
<%= render @discussion.开发者_开发技巧posts %>
<%= link_to 'Edit', edit_discussion_path(@discussion) %> |
<%= link_to 'Back', discussions_path %>
_post.html.erb
<div class="post">
<p>
<b>Content:</b>
<%= post.content %>
</p>
<%= link_to 'Edit', edit_post_path(post) %> |
<%= link_to 'Back', posts_path %>
</div>
This will cause an error at the 'edit' and 'back' link_to methods, because the new post object I built will become part of the @discussion.posts, and since that new post is not saved, the edit_post_path url helper will give out "No route matches" error(it can't find that unsaved post).
If I want to keep 'edit' and 'back' link_to methods, I have to filter out the newly built (but not saved) object. But somehow I feel that what I have done may be hackish, and want to ask if there is any better practice to achieve my goal.
If you don't need the discussion_id
when submitting the new Post
form, then you can simply do
@post = Post.new
If you do need discussion_id
set on the new Post
object then you can do that without adding the new object to @discussion.posts
@post = Post.new(:discussion => @discussion)
精彩评论