为什么我的rails会在选择后显示动作创建新记录?

时间:2011-10-19 22:58:17

标签: ruby-on-rails ruby insert controller

Rails nooby所以我不知道提供什么信息。基本上,当我从图片控制器调用我的show动作时,会插入一条新的评论记录。我的输出如下:

Started GET "/pictures/2" for 127.0.0.1 at Wed Oct 19 18:43:24 -0400 2011
  Processing by PicturesController#show as HTML
  Parameters: {"id"=>"2"}
  Picture Load (0.2ms)  SELECT "pictures".* FROM "pictures" WHERE "pictures"."id" = $1     LIMIT 1  [["id", "2"]]
  Comment Load (0.4ms)  SELECT "comments".* FROM "comments" WHERE "comments"."picture_id"     = 2
   (0.2ms)  BEGIN
  SQL (0.7ms)  INSERT INTO "comments" ("comment", "created_at", "downvote", "picture_id",     "updated_at", "upvote") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id"  [["comment", nil],     ["created_at", Wed, 19 Oct 2011 22:43:24 UTC +00:00], ["downvote", nil], ["picture_id", 2],     ["updated_at", Wed, 19 Oct 2011 22:43:24 UTC +00:00], ["upvote", nil]]
   (1.1ms)  COMMIT
Rendered pictures/show.html.erb within layouts/application (32.2ms)
Completed 200 OK in 51ms (Views: 41.0ms | ActiveRecord: 7.5ms)

显示控制器:

def show
  @picture = Picture.find(params[:id])
  @comments = @picture.comments
  respond_to do |format|
    format.html # show.html.erb
    format.json { render :json => @picture }
  end
end

显示视图:

<p id="notice"><%= notice %></p>

<h2><%= @picture.title %></h2> <br />
    <ul class="media-grid">
     <li>
     <a href="#">
     <%= image_tag @picture.url %>
    </a>
    </li>
  </ul>
<table>
<% @comments.each do |comment| %>
  <tr>
    <td><%= comment.comment %></td>
<td><%= comment.upvote %></td>
<td><%= comment.downvote %></td>
</tr>
<% end %>
</table>
<%= form_for [@picture, @picture.comments.create] do |f| %>
  <%= f.label "Comment:" %><br />
  <%= f.text_field :comment %>
  <%= f.submit %>
<% end %>

<%= link_to 'Back', pictures_path %>

型号:

class Comment < ActiveRecord::Base
  belongs_to :picture
end

class Picture < ActiveRecord::Base
  has_many :comments
end

1 个答案:

答案 0 :(得分:2)

据我所知,你不想使用

<%= form_for [@picture, @picture.comments.create] do |f| %>

<%= form_for [@picture, @picture.comments.new] do |f| %>