I'm new to rails and I'm building a small app. I have an album model
that can have many comments. Albums belong to families, laid out in
routes.rb. I want to be able to add comments in my /albums/
show.html.erb. I currently have this in the album controller:
def post_comment
@comment = Comment.new(params[:comment])
respond_to do |format|
if Comment.save
flash[:notice] = "Comment added"
format.html { redirect_to(@family, @album) }
end
end
end
and in the show.html.erb
<div id="comments">
<center>
<% if @album.has_comments? %>
<% for comment in @album.comments %>
<%= comment.user.login %> on <%= comment.created_at %>
<%=h comment.text %>
<% end %>
<% end %>
</center>
</div>
<%= link_to_function "Add another comment" do |page|
page.insert_html :bottom, :comments, :partial => 'comments' end %>
and the _comments.html.erb looks like:
<% form_for(:comment, :url => {:action => "post_comment"}) do |f| %>
...
<% end %>
routes.rb:
map.resources :families do |families|
families.resources :albums
end
The problem is that whenever I hit submit in the Albums show view, it
re-directs me to /albums/post_comment, which doesn't work because it
can't find a family.id - I would like to remain on the /family/id/
album/id page. Is there something else I need to do here because the
Album controller is a nested resource?
ActiveRecord::RecordNotFound (Couldn't find Family without an ID):
So, I believe that the action in the album controller is working
correctly, since it is being processed, and all of the data is passing
through correctly in the parameters, but it is still directing me back
to /album/post_comments instead of /families/id/albums/id - any ideas?
def post_comment
@comment = Comment.new(params[:comment])
respond_to do |format|
if Comment.save
flash[:notice] = "Comment added"
format.html { redirect_to(@family, @album) }
end
end
end
change the arguments in redirect_to
@album to @comment.album
and
@family to @comment.album.family
OR
change the whole line
format.html { redirect_to(@family, @album) }
to
format.html { redirect_to(family_album_path(@comment.album.family,
@comment.album)) }