与用户和帖子建立关联时,评论 table 中的空白 user_id

Blank user_id in comments table when making associations with both users and posts

我正在使用我们通过 rails 教程构建的注册和登录作为我正在制作的 Reddit 克隆的基础。目前应用程序正常运行,除了评论中的 user_id table 在我发表评论时为空白,link_id 存在且正确,因此我可以对 [= 发表评论73=]。 links table 中的 user_id 也存在并且正确。

我很确定我犯的错误是在 comments_controller.rb 的创建操作中,但它也可能是我最初的迁移。令我(作为新手)感到困惑的是,我以前曾使用 rails 4.1.8 和设备以当前形式使用过它。但是,以 rails 教程为基础,将此方法与 rails 4.2.1 一起使用时,它不起作用。我是新来的,所以我希望我已经正确地制定了 post 并提供了足够的信息,以便有人可以给我一些关于问题的指示

评论控制器

    before_action :logged_in_user, only: [:create, :destroy]

def create
    @link = Link.find(params[:link_id])
    @comment = @link.comments.create(params[:comment].permit(:link_id, :body))
    @comment.user = User.find(current_user.id)
    redirect_to link_path(@link)
end

def destroy
    @link = Link.find(params[:link_id])
    @comment = @link.comments.find(params[:id])
    @comment.destroy
    redirect_to link_path(@link)
end

private

def logged_in_user
    unless logged_in?
        flash[:danger] = "Please log in."
        redirect_to login_url
    end
end

表格 app/views/links/show.html.erb

<h2 class="comment-count"><%= pluralize(@link.comments.count, "comment") %></h2>
<%= render @link.comments %>
<%= form_for([@link, @link.comments.build]) do |f| %>
<%= render 'comments/fields', f: f %>
<%= f.submit "Save Comment", class: 'btn btn-primary margin-bottom-10' %>
<% end %>

部分 app/views/comments/_comment.html.erb

<p class="comment_body"><%= comment.body %></p>
<p class="comment_time"><%= time_ago_in_words(comment.created_at) %> Ago </p>

app/views/comments/_fields.html.erb

<%= render 'shared/comment_error_messages' %>
<%= f.label :body %>
<%= f.text_area :body, class: 'form-control' %>

路线 config/routes.rb

resources :links do
member do
  put "like", to: "links#upvote"
  put "dislike", to: "links#downvote"
end
resources :comments
end

型号 app/models/link.rb

belongs_to :user
has_many :comments, dependent: :destroy

app/models/comment.rb

belongs_to :user
belongs_to :link
validates :body,  presence: true

app/models/user.rb

has_many :links, dependent: :destroy

迁移

class CreateComments < ActiveRecord::Migration
    def change
    create_table :comments do |t|
    t.integer :link_id
    t.text :body
    t.references :user, index: true, foreign_key: true

    t.timestamps null: false
   end
   add_index :comments, :link_id
   end
end

希望这足够好 [=7​​4=] 我已经包含了您需要的所有内容,所以有人可以帮助我,这是一个菜鸟错误,但我看不到它。提前致谢。

此致

目前,您正在创建一个 comment 而没有为它保存 user_id。试试下面的代码

#comments_controller.rb
def create
  @link = Link.find(params[:link_id])
  @comment = @link.comments.new(params[:comment].permit(:link_id, :body))
  @comment.user = User.find(current_user.id)
  @comment.save
  redirect_to link_path(@link)
end