I found plenty of example on how to construct a multi-model form and multi-model display. But what if I want to have separate forms and displays?
post.rb:
class Post < ActiveRecord::Bas
has_many :comments, dependent: :destroy
attr_accessible :comments_attributes
accepts_nested_attributes_for :comments
end
comment.rb:
class Comment < ActiveRecord::Base
belongs_to :post
end
posts_controller.rb:
def new
@post = Post.new
@post.comments.build
...
end
routes.db:
resources posts do
resources comments
end
I have a link to post comments index in my post index:
views/posts/index.html.erb:
...
<%= link_to 'Comments', post_comments_path(post) %>
...
Post and Comment each have their own scaffold generated form (not nested).
<%= form_for(@post) do |f| %>
...
<%= form_for(@comment) do |f| %>
...
In the comments index I loop over post comments:
views/comments/index.html.erb:
<% @post = Post.find(params[:post_id]) %> //works fine
<% @post.comments.each do |comment| %>
...
<% end %>
Yet after adding a new comment (under a specific post id) the table in the post comments index is empty!
Please help.
Thanks 🙂
I figured it out.
In the comments forms it should be:
Paths should be used like:
etc.
In the Comments controller:
etc.
Hope others will find this useful!