我想在用户视图的顶部附近显示该帖子的用户评论(如果他们已经发表评论的话)。因此,在我的Comment控制器中,我想针对该特定帖子将变量@user_comment初始化为该特定用户的comment对象。我知道这不是最复杂的问题。
这是我到目前为止的内容:
相关评论控制器
def show
@comments = Comment.find(params[:id])
@post = Post.find(params[:id])
@user = current_user.id
@user_comment = Comment.where(post_id: @post, user_id: @user)
#@user_comment is the local variable im trying to set to the user's comment for that specific post.
end
相关架构
create_table "posts", force: :cascade do |t|
t.string "title"
t.string "content"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "comments", force: :cascade do |t|
t.text "content"
t.integer "post_id"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "comments", ["post_id"], name: "index_comments_on_post_id"
add_index "comments", ["user_id"], name: "index_comments_on_user_id"
显示页面
<% if @user_comment.nil? || !user_signed_in? %>
<!-- Normal comment form -->
<% else %>
<!-- I want to show the user's comment here, I tried something along the lines of @user_comment.content, but it says it's not a valid method, which gives me the idea I didn't initialize it properly. -->
<% end %>
如果大家都知道一个很好的资源,可以很好地教授查询,那么我很乐意仔细研究一下,因为显然这是我前进所需要知道的。
似乎有些令人困惑的是您要在评论显示页面上呈现“帖子”。似乎更合乎逻辑的是在展后页面上呈现“评论”。
岗位控制器
def show
@post = Post.find(params[:id])
@comment = @post.comments.where(user_id: current_user) # This uses an association
end
发布显示页面
<% if @comment.nil? || !user_signed_in? %> <!-- Here I use the @comment variable -->
<!-- Normal comment form -->
<% else %>
<!-- I want to show the user's comment here, I tried something along the lines of @user_comment.content, but it says it's not a valid method, which gives me the idea I didn't initialize it properly. -->
<% end %>
邮政模型
class Post < ActiveRecord::Base
has_many :comments # This creates the association to grab the comments
end
您的密码
在注释控制器中,您具有以下内容:
@comments = Comment.find(params[:id])
@post = Post.find(params[:id])
帖子和评论可能不会相同id
。并看到它是注释控制器,id
通过params传递的将是id
注释的。所以,如果你是做通过评论控制器的一切,你可能需要使用类似的关联@post = @comment.post
。我更改@comments
为@comment
并使用了关联。评论模型将需要belongs_to :post
使关联工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句