Rails不会将我的外键保存到数据库中

时间:2010-10-11 08:22:27

标签: ruby-on-rails associations

所以基本上我有两个模型,Entry和Comment。 我有关联设置,以便Entry有很多评论:

class Entry < ActiveRecord::Base
has_many :comments
end

评论属于一个条目:

class Comment < ActiveRecord::Base
belongs_to :entry
end

在我的数据库模式中,我使用名为entry_id的列设置了comments表。 据我所知,这是我设置关联所需的全部内容。 但是,当我保存评论时,它不会将entry_id保存到数据库中。

我可以确认entry_id是在表单中传递的。这是发送到控制器的params变量的转储。

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

任何想法?

编辑: 这是我的观点,内置评论表:

<% @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 %>

我将通讯作为嵌套路线:

  resources :entries do
resources :comments
  end

1 个答案:

答案 0 :(得分:2)

您的参数中的entry_id不在您的评论中。你需要:

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

在您的表单中,您的entry_id需要在评论部分。留言[entry_id]

如果您想了解更多信息,我们需要您的观点。

你有两个选择

1)在表单中添加entry_id

<%= 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)将其添加到您的创建动作

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

您遇到此问题是因为您嵌套了表单。

相关问题