views:

16

answers:

1

So basically I have two models, Entry and Comment. I have the association setup so that Entry has many Comments:

class Entry < ActiveRecord::Base
has_many :comments
end

And a comment belongs to an entry:

class Comment < ActiveRecord::Base
belongs_to :entry
end

In my database schema I have setup the comments table with a column called entry_id. To my knowledge, this is all I needed to do to setup an association. However when I save a comment, it does not save the entry_id into the database.

I can confirm that the entry_id is being passed in the form. Here is a dump of the params variable being sent to the controller.

{"comment"=>{"comment"=>"ghgghgh"},
"commit"=>"Create Comment",
"format"=>"",
"entry_id"=>"1",
"authenticity_token"=>"G4uH8smdA2eeKeTXbD9NbenKH4AbWLyJuPWQzRcn6CI=",
"utf8"=>"✓"}

Any Ideas?

EDIT: This is my view with the comment form built in:

<% @entry.each do |e| %>
<div class="entry">
<p><%= e.entry %></p>
<small>Posted by <%= e.author %> at <%= e.created_at.strftime("%I:%M%p %m/%d/%Y") %></small>
<% if e.comments.nil? %>
    <p>No Comments</p>
<% else %>
    <% e.comments.each do |c| %>
    <blockquote><%= c.comment %></blockquote>
    <% end %>
<% end %>
<%= form_for @comment, :url => entry_comments_path(e, @comment) do |f| %>
<%= f.label :comment %>
<%= f.text_area :comment %>
<%= f.submit %>
<% end %>
</div>
<hr />
<% end %>
<%= button_to "Write A Message", new_entry_path, :method => :get %>

I have commments as a nested route:

  resources :entries do
resources :comments
  end
+1  A: 

The entry_id is not in your comment in your params. You need have :

 {"comment"=>{"comment"=>"ghgghgh", "entry_id"=>"1"},
"commit"=>"Create Comment",
"format"=>"",
"authenticity_token"=>"G4uH8smdA2eeKeTXbD9NbenKH4AbWLyJuPWQzRcn6CI=",
"utf8"=>"✓"}

In your form, you entry_id need to be in comment part. comment[entry_id]

If you want more information, we need your view.

You have two choice

1) add the entry_id in your form

<%= form_for @comment, :url => entry_comments_path(e, @comment) do |f| %>
<%= f.label :comment %>
<%= f.text_area :comment %>
<%= f.hidden_field :entry_id, e.id
<%= f.submit %>

2) add it in your create action

def create
  Comment.create(params[:comment].merge(:entry_id => params[:entry_id])
end

You have this problem because you nested your form.

shingara
Thanks for the response. I have added my view to the question - hopefully you can point out what I need to change
Nick Barrett
I update my answer with several information.
shingara
great informative answer, thanks
Nick Barrett