[英]Comments that belong_to Post and belong_to User
I'm trying to add comments to a Post model我正在尝试向帖子 model 添加评论
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :user #should this be has_one :user instead?
....
How do I set up my Comment new and creation actions to get both current_user as well as the current post?如何设置我的新评论和创建操作以同时获取 current_user 和当前帖子?
guides.rubyonrails.org suggested建议使用 guides.rubyonrails.org
Controller: Controller:
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(params[:comment])
redirect_to post_path(@post)
end
View看法
<%= form_for([@post, @post.comments.build]) do |f| %>
...
However this only seems to be aiming to associate with the post and not also the user.然而,这似乎只是为了与帖子相关联,而不是与用户相关联。 How can I set up both associations?我怎样才能建立这两个协会?
I assume you have a current_user()
method somewhere in your controller.我假设您的 controller 中某处有一个current_user()
方法。
So this should do it:所以这应该这样做:
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.build(params[:comment])
@comment.user = current_user
@comment.save
redirect_to post_path(@post)
end
Deradon answered the question well but I prefer to have that logic within the new comment form itself. Deradon 很好地回答了这个问题,但我更喜欢在新评论表单本身中包含该逻辑。 For example, instead of calling those variables you can have:例如,您可以不调用那些变量:
app/views/comments/_form.html.erb:应用程序/视图/评论/_form.html.erb:
<%= f.hidden_field :user_id, value: current_user.id %>
<%= f.hidden_field :post_id, value: @post.id %>
This assumes of course that your new comment form is embedded within the 'post show' page, so that @post is available:这当然假设您的新评论表单嵌入在“post show”页面中,因此 @post 可用:
app/views/posts/show.html.erb:应用程序/视图/帖子/show.html.erb:
<body>
<%= render @post %>
<%= render 'comments/_form' %>
</body>
This will add post_id and user_id directly into the db for a new comment.这会将 post_id 和 user_id 直接添加到数据库中以获取新评论。 Also, don't forget to make an index for those foreign keys so the database has quicker access.另外,不要忘记为这些外键创建索引,以便更快地访问数据库。 If you don't know how, google it!如果你不知道如何,谷歌它!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.