具有带评论的博客的铁路应用程序

Rail Application having blogs with comments

我正在 Rails 上学习 Ruby 并且我正在使用 Rails 4. 按照 Rails 关于制作带评论的博客应用程序的教程,作者写了这个在 comments_controller.rb

中创建评论
def create
@post=Post.find(params[:post_id])
@comment=@post.comments.build(params[:post].permit[:body])
redirect_to @post_path(@post)
end

在部分中:_form.html.erb

<%= form_for([@post, @post.comments.build]) do |f| %>
<h1><%= f.label :body %></h1><br />
<%= f.text_area :body %><br />
<%= f.submit %>
<% end %>

我想知道是否可以只让当前用户评论 post,在用户模型和评论模型之间建立所有适当的关联,以便在显示评论时,我可以从中检索信息用户通过评论。显然,我不只是想使用

before_action :authenticate_user!

因为我想要用户和评论之间的关联。

如果我没理解错的话,您已经准备好模型之间的适当关联,问题是如何更新控制器的动作以使其工作。

如果我对你的Comment模型有正确的理解,除了post,它还有bodyuser属性。

首先,您应该更新您当前的代码:

@comment = @post.comments.build(params[:post].permit[:body])

看起来像这样:

@comment = @post.comments.build(body: params[:post].permit[:body])

要正确设置 body 属性,并创建与 current_user 的正确关联非常简单:

@comment = @post.comments.build(body: params[:post].permit[:body],
  user: current_user)

此时评论还没有保存,所以你有两个选择:

  1. 创建评论后您可以手动保存它:

    @comment.save

或 2. 将 build 替换为 create:

@comment = @post.comments.create(body: params[:post].permit[:body],
  user: current_user)

希望对您有所帮助!

您正在学习的教程不太好。


以下是您应该查看的内容:

#config/routes.rb
resources :posts do
   resources :comments #-> url.com/posts/:post_id/comments/new
end

#app/controllers/comments_controller.rb
class CommentsController < ApplicationController
   def create
      @post = Post.find params[:post_id]
      @post.comments.new comment_params #-> notice the use of "strong params" (Google it)
      @post.save
   end

   private

   def comment_params
       params.require(:comment).permit(:body)
   end
end

要将 User 添加到 Comment,您需要这样做:

#config/routes.rb
resources :posts do
   resources :comments #-> url.com/posts/:post_id/comments/new
end

#app/models/user.rb
class User < ActiveRecord::Base
   has_many :comments
end

#app/models/comment.rb
class Comment < ActiveRecord::Base
   belongs_to :user
   belongs_to :post
end

#app/controllers/comments_controller.rb
class CommentsController < ApplicationController
   before_action :authenticate_user! #-> only if you're using devise

   def create
      @post = Post.find params[:post_id]
      @comment = current_user.comments.new comment_params
      @comment.post = @post
      @comment.save
   end

   private

   def comment_params
      params.require(:comment).permit(:body)
   end
end

如果您不确定是否要建立 has_many/belongs_to 关系,您应该创建您的表 like this: