Rails:将注释ID与特定的Micropost id匹配

时间:2012-02-27 17:48:27

标签: ruby-on-rails ruby ruby-on-rails-3 post associations

目前我有一条属于微博的评论,但问题是,当用户创建评论时,评论会以微博ID存储在数据库中,但id不是针对特定的微博而是看似好像评论只是将微博ID增加了+1。非常困惑,非常感谢任何帮助。谢谢!

评论模型

class Comment < ActiveRecord::Base
  attr_accessible :content, :user_id, :micropost_id
  belongs_to :micropost
  belongs_to :user

  validates :content, presence: true, length: { maximum: 140 }


  default_scope order: 'comments.created_at DESC'
end

Micropost模型

class Micropost < ActiveRecord::Base
  attr_accessible :title, :content, :view_count
  belongs_to :user
  has_many :comments
  accepts_nested_attributes_for :comments
end

评论控制器

class CommentsController < ApplicationController 
  def create
    @micropost = Micropost.find(params[:micropost_id])
    @comment = @micropost.comments.build(params[:comment])
    @comment.user_id = current_user.id
    @comment.save 
      respond_to do |format|
      format.html 
      format.js
    end
  end
end

表格

<div class="CommentField">
<%= form_for ([@micropost, @micropost.comments.new]) do |f| %>
<%= f.text_area :content, :class => "CommentText", :placeholder => "Write a Comment..." %>
<div class="CommentButtonContainer">
<%= f.submit "Comment", :class => "CommentButton b1" %>
</div>
<% end %>
</div>

路线

  resources :microposts do
    resources :comments
  end

Raked Routes

micropost_comments     GET    /microposts/:micropost_id/comments(.:format)          comments#index
                       POST   /microposts/:micropost_id/comments(.:format)          comments#create
 new_micropost_comment GET    /microposts/:micropost_id/comments/new(.:format)      comments#new
edit_micropost_comment GET    /microposts/:micropost_id/comments/:id/edit(.:format) comments#edit
     micropost_comment GET    /microposts/:micropost_id/comments/:id(.:format)      comments#show
                       PUT    /microposts/:micropost_id/comments/:id(.:format)      comments#update
                       DELETE /microposts/:micropost_id/comments/:id(.:format)      comments#destroy

1 个答案:

答案 0 :(得分:1)

我认为这里的问题是你投入了多少工作。 Rails旨在了解大部分内容,而无需执行您正在执行的操作。我的建议是将你的评论控制器改为这样的

class CommentsController < ApplicationController 
  def create
    @comment = Comment.new(params[:comment])
    @comment.save 
      respond_to do |format|
      format.html 
      format.js
    end
  end
end

因为你要通过另一部分呈现你的评论部分形式,你需要传递它上面相关帖子的局部变量。

    “comments / form”,:locals =&gt; {:micropost =&gt; micropost}%&gt;

和你的表格是这样的

<div class="CommentField">
<%= form_for ([micropost, @comment]) do |f| %>
<%= f.text_area :content, :class => "CommentText", :placeholder => "Write a Comment..." %>
<div class="CommentButtonContainer">
<%= f.submit "Comment", :class => "CommentButton b1" %>
</div>
<% end %>
</div>

在我的所有rails应用程序中,这就是我需要做的所有关联,以便它自己正确地分配ID。我相信我会解决这个问题。