我如何评论我的帖子?

我如何评论我的帖子?

问题描述:

我正在尝试添加用户添加评论到我的rails站点上的帖子的能力。我如何评论我的帖子?

我在我的数据库中有一个Posts表和一个Users表。我正在使用足智多谋的路线在我的帖子控制器的'show'动作上显示各个帖子。我希望能够在帖子下方显示评论框,以便用户输入评论,然后点击提交并让它创建评论。

我试着做一个评论模型,给他们一个belongs_to关系的用户和帖子。我还将has_many关系添加到用户和发布模型。然后,我尝试让评论控制器使用“创建”操作来处理每个帖子“显示”操作的表单。

我遇到了无法获取post_id以注入新评论的问题。我可以通过从用户会话中获取user_id来获取user_id,但传递给评论控制器上的“创建”操作的唯一内容就是通过表单评论的实际文本。

这是添加此功能的好方法吗?必须有更好的做法,或者我只是想念一些东西。

我的帖子控制器“秀”行动:

#PostsController.rb 

def show 
    @post = Post.where(:id => params[:id]).first 
    if @post.nil? 
    flash[:error] = "Post does not exist" 
    redirect_to(root_path) 
    end 
    @comment = Comment.new 
end 

在“显示”视图的形式在PostsController“显示”行动:

#views/posts/show.html.erb 

<%= form_for @comment do |f| %> 
    <%= f.text_area(:content, :size => '20x10', :class => 'textarea') %> 
    <%= f.submit('Create Post', class: 'button button-primary') %> 
<% end %> 

我的意见控制器“创建”行动:

#CommentsController.rb 

def create 
    @comment = Comment.new(params.require(:comment).permit(:content, :post_id, :user_id)) 
    @comment.user_id = session[:user_id] 
    #Need to set post_id here somehow 
    if @comment.valid? 
    @comment.save 
    flash[:success] = "Comment added successfully." 
    redirect_to(post_path(@comment.post)) 
    else 
    @error = @comment.errors.full_messages.to_s 
    @error.delete! '[]' 
    flash.now[:error] = @error 
    render('posts/show') 
    end 
end 

我的Post模型:

class Post < ApplicationRecord 
    belongs_to :subject 
    belongs_to :user 
    has_many :comments 

    validates :title, :presence => true, 
        :length => {:within => 4..75} 


    validates :content, :presence => true, 
         :length => {:within => 20..1000} 
end 

我的评论模式:

class Comment < ApplicationRecord 
    belongs_to :user 
    belongs_to :post 

    validates :content, :presence => true, 
         :length => {:within => 6..200} 

end 
+0

您是否正在学习任何教程?请更新您的问题与帖子和评论模型 – Hizqeel

+0

你到达那里,这并不难,尝试深入挖掘在线资源,你会发现它很容易。顺便说一句,'@post = Post.where(:id => params [:id])。first' >>>>你可以使用'.find'与ID,[.find](http:// apidock。 com/rails/ActiveRecord/FinderMethods/find) – tkhuynh

+0

@Hizqeel我在Lynda上使用了一个关于我的初始应用程序创建的教程,但是我无法在线找到有关如何添加注释的资源。我为我的模型添加了代码。 – Kecoey

在您的文章控制器表演动作,使新的评论属于后

def show 
    @post = Post.where(:id => params[:id]).first 
    if @post.nil? 
    flash[:error] = "Post does not exist" 
    redirect_to(root_path) 
    end 
    @comment = @post.comments.new # <--- here's the change 
end 

然后POST_ID字段添加到窗体作为隐藏字段

<%= form_for @comment do |f| %> 
    <%= f.hidden_field :post_id %> 
    <%= f.text_area(:content, :size => '20x10', :class => 'textarea') %> 
    <%= f.submit('Create Post', class: 'button button-primary') %> 
<% end %> 

而且你应该不用改变评论cont滚筒创建动作

+0

只需检查并确保它工作。看起来像它!谢谢!虽然我对控制器演出中的新行感到有点困惑。我不确定它为什么有效,只是用“@comment = Comment.new”发表新评论不会 – Kecoey

+0

'@comment = @ post.comments.new'与'@comment = Comment.new (post_id:@ post.id)'。您只需要为注释设置post_id,然后确保表单保留了它。 – TerryS