Micropost对用户页面的评论(Ruby on Rails)

在用户页面上我有很多微博,我想为每个微博添加评论表和评论。

我有三个模型:User,Micropost,Comment。

user.rb

class User < ActiveRecord::Base has_many :microposts, dependent: :destroy has_many :comments end 

micropost.rb

 class Micropost < ActiveRecord::Base belongs_to :user has_many :comments, dependent: :destroy end 

comment.rb

 class Comment < ActiveRecord::Base attr_accessible :comment_content belongs_to :user belongs_to :micropost validates :comment_content, presence: true validates :user_id, presence: true validates :micropost_id, presence: true end 

comments_controller.rb

 class CommentsController < ApplicationController def create @comment = current_user.comments.build(params[:comment]) if @comment.save flash[:success] = "Comment created!" redirect_to current_user else render 'shared/_comment_form' end end end 

_micropost.html.erb

     Posted  ago.     

评论表

   

每个微博都必须有自己的评论。 在我的数据库中我有评论表

id / comment_content / user_id / micropost_id

列。

评论没有创建,因为RoR无法理解哪个微博属于这个新评论。 我该怎么做才能在我的数据库中获得所有需要的信息?

UPDATE

users_controller

  def show @user = User.find(params[:id]) @microposts = @user.microposts.paginate(page: params[:page]) @comment = Comment.new end 

microposts_controller

  def create @micropost = current_user.microposts.build(params[:micropost]) if @micropost.save flash[:success] = "Micropost created!" redirect_to current_user else render 'shared/_micropost_form' end end 

解!!!

非常感谢carlosramireziii和Jon! 他们都是对的

comments_controller

  def create @micropost = Micropost.find(params[:micropost_id]) @comment = Comment.new(params[:comment]) @comment.micropost = @micropost @comment.user = current_user if @comment.save flash[:success] = "Comment created!" redirect_to current_user else render 'shared/_comment_form' end end 

_micropost.html.erb

  

评论表

  

的routes.rb

 resources :microposts do resources :comments end 

尝试将当前微博传递给评论部分

 <%= render 'shared/comment_form', micropost: micropost %> 

然后将微博添加到注释form_for调用

 <%= form_for([micropost, @comment]) do |f| %> 

确保您的路由是嵌套的

 # in routes.rb resources :microposts do resources :comments end 

然后在CommentsController构建微博的CommentsController

 def create @micropost = Micropost.find(params[:micropost_id]) @comment = @micropost.comments.build(params[:comment]) ... end 

我会在routes.rb文件中使用嵌套资源进行微博和类似的注释:

 resources :microposts do resources :comments end 

然后在您通过micropost_comments_path(@micropost) url帮助程序访问的注释控制器中,您可以执行以下操作以在create操作中构建关联:

 def create @micropost = Micropost.find(params[:micropost_id]) @comment = Comment.new(params[:comment]) @comment.micropost = @micropost @comment.user = current_user if @comment.save ... end 

您可以使用merge方法减少代码行数,但我发现这有时会降低代码的可读性,因为如果在validation错误后重新显示表单,您将需要@micropost对象,您也可以只提取记录。