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