如何设置一个局部变量等于用户在帖子中的特定评论?可能很简单

时间:2016-06-04 18:00:40

标签: ruby-on-rails

如果用户对该帖子发表评论,我想在我的视图顶部附近显示用户的评论。因此,在我的Comment控制器中,我想将变量@user_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 %>

如果你们都知道一个很好的教学资源,那么我很乐意去研究它,因为很明显这是我需要知道的事情。

1 个答案:

答案 0 :(得分:1)

似乎有点令人困惑的是你想要在评论节目页面上呈现“帖子”。更合乎逻辑的是在帖子显示页面上呈现“评论”。

后置控制器

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将是注释的id。因此,如果 通过评论控制器执行所有操作,您可能希望使用@post = @comment.post之类的关联。我将@comments更改为@comment并使用了关联。评论模型需要belongs_to :post才能使关联有效。