簡體   English   中英

“注釋”控制器中的“創建”方法不起作用。 軌道

[英]The Create method in a Comments controller is not working. Rails

我知道針對該主題也曾提出過類似的問題,但我已經閱讀了所有這些問題,因此無法找到明確的解決方案。 在陳述問題之前,我將發布所有必需的代碼。

型號:

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :scoreboard
  end

class User < ActiveRecord::Base 
  has_many :scoreboards, dependent: :destroy
  has_many :comments, dependent: :destroy
end

class Scoreboard < ActiveRecord::Base
  belongs_to :user
  has_many :teams, dependent: :destroy
  has_many :comments, dependent: :destroy
end

記分板類似於文章頁面,用戶可以在其中發表評論。

評論的遷移:

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

      t.timestamps null: false
    end
    add_foreign_key :comments, :users
    add_foreign_key :comments, :scoreboards
  end
end

問題在於注釋控制器中create方法。 這是該方法的代碼:

def create
     @scoreboard = Scoreboard.find(params[:scoreboard_id])
     @comment.user_id = current_user.id
     @comment = @scoreboard.comments.build(comment_params)
     redirect_to scoreboard_url(@comment.scoreboard_id)
    end

current_user方法位於單獨文件夾中的幫助文件中。 每當我提交表單以發表新評論時,都會出現以下錯誤:

undefined method `user_id=' for nil:NilClass

堆棧上的一個問題表明,注釋中需要一個user_id列,而當我嘗試遷移它時,則無法創建重復的列。 是否因為遷移中已經存在用戶的外鍵? 我可能做錯了什么?

錯誤非常簡單:

 @comment.user_id = current_user.id
 @comment = @scoreboard.comments.build(comment_params)

您正在調用@comment而不預先定義它。

應該是這樣的:

 @comment = @scoreboard.comments.build comment_params
 @comment.user_id = current_user.id

堆棧中的一個問題表明注釋中需要一個user_id列

為了澄清起見,他們指的是Comment模型的foreign_key

您必須記住,Rails是建立在關系數據庫之上的:

在此處輸入圖片說明

無論您使用哪種SQL變體,您仍將以關系方式使用它。 Rails已向其中添加ActiveRecord“對象關系映射器”

簡而言之,這使Rails能夠通過不同的查詢等調用關聯數據。 @scoreboard.comments關聯。

在后端,Rails必須計算哪些數據與另一個相關。 在使用適當的關系數據庫結構(包括使用foreign_keys

這就是創建關聯對象時必須分配諸如user_id 但是,有一個技巧可以使它更加簡潔:

#app/controllers/comments_controller.rb
class CommentsController < ApplicationController
   def create
     @scoreboard = Scoreboard.find params[:scoreboard_id]
     @comment    = @scoreboard.comments.build comment_params
   end

   private

   def comment_params
      params.require(:comment).permit(:params).merge(user_id: current_user.id)
   end
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM