ruby-on-rails - 铁路应用程序有带有评论的博客

标签 ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4

我正在学习 Ruby on Rails,并且正在使用 Rails 4。按照有关制作带有评论的博客应用程序的 Rails 教程,作者编写了此内容以在 comments_controller.rb 中创建评论

def create
@post=Post.find(params[:post_id])
@<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="84e7ebe9e9e1eaf0b9c4f4ebf7f0aae7ebe9e9e1eaf0f7aae6f1ede8e0" rel="noreferrer noopener nofollow">[email protected]</a>(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 %>

我想知道是否只能让当前用户对帖子发表评论,在用户模型和评论模型之间建立了所有适当的关联,以便在显示评论时,我可以通过评论从用户那里检索信息。显然,我不仅仅是想使用

before_action :authenticate_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

要将用户添加到评论,您需要执行以下操作:

#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 :

enter image description here

关于ruby-on-rails - 铁路应用程序有带有评论的博客,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34466372/

相关文章:

ruby-on-rails - 带有 formtastic 的 rails3-jquery-autocomplete 引用 ID

ruby-on-rails - Ruby 获取深度嵌套的 JSON API 数据

ruby-on-rails-3 - 模型中默认范围内的参数

ruby-on-rails - 在 Ruby on Rails-3 中使用 'form_tag' 和命名空间提交表单

ruby-on-rails - rails admin + carrierwave 更新破坏了图像 url

ruby-on-rails - `ActiveSupport::Cache::FileStore` key 限制是多少?

ruby-on-rails - 如何使用带有参数的 Rails 命名路由助手?

ruby-on-rails - Ruby 类图不显示在 RubyMine 的图表菜单中

ruby-on-rails - 如何修复丢失的模板错误?

ruby - Rails 3.2.8 - 如何从 Rails 获取周数?