我正在嘗試一個簡單的功能,用戶可以對調查帖子發表評論,但評論 .user.username 不起作用,它正在呈現 comment.user 但不支持用戶屬性
create_table "comments", force: :cascade do |t|
t.string "content"
t.integer "inquest_id"
t.integer "user_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["inquest_id"], name: "index_comments_on_inquest_id"
t.index ["user_id"], name: "index_comments_on_user_id"
end
評論模型
class Comment < ApplicationRecord
belongs_to :inquest
belongs_to :user
end
user_model 很簡單,有很多評論關聯
控制器的注釋創建方法
def create
@comment = Comment.new(comment_params)
pp comment_params
@inquest = Inquest.find(params[:inquest_id])
@comment = Comment.new(comment_params)
@comment.inquest = @inquest
@comment.user = current_user
respond_to do |format|
if @comment.save
format.js do
@inquest = Inquest.find(params[:inquest_id])
end
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
我正在審訊的 show.html.erb 中發表評論
Showing /Users/zunairaihsan/Desktop/fyp_ed_bolt/app/views/inquests/show.html.erb
where line #123 raised:
undefined method `user_name' for nil:NilClass
我已經嘗試了大多數可能的方法,但它不起作用。請讓我知道我錯在哪里
uj5u.com熱心網友回復:
我假設,在inquests/show.html.erb您顯示多個評論時,例如
<%= @inquest.comments.each do |comment| %>
<%= comment.user.user_name %>
<%= comment.content %>
<% end %>
許多評論將毫無問題地呈現。模型Comment和資料庫不允許user_id.nil
但看起來一個評論在用戶表user_id中沒有對應的。id當你試圖弄清楚發生了什么并洗掉user_name
<%= @inquest.comments.each do |comment| %>
<%= comment.user %>
<%= comment.content %>
<% end %>
鬼鬼祟祟的評論可能不會向您顯示任何內容,comment.useris nil,并且因為您沒有對其進行驗證comment.content也可能是 nil。
首先,洗掉評論而不user驗證這是問題所在:
# this is fast enough for a few thousand comments
>> Comment.find_each { |comment| comment.destroy unless comment.user }
在這之后inquests/show.html.erb應該作業。
為確保不再發生這種情況:
class User
# this will delete all `user.comments` when you destroy `user`
has_many :comments, dependent: :destroy
# ...
end
要真正確保不會再次發生這種情況:
class CreateComment < ActiveRecord::Migration[7.0]
def change
create_table :comments do |t|
t.references :user, null: false, foreign_key: true
# ...
end
end
end
有了foreign_key約束,如果用戶有評論,您的資料庫將不會讓您銷毀用戶。這與dependent: :destroy. 如果你洗掉一個用戶并且 rails 自動銷毀 all user.comments,那么資料庫不會抱怨。
inquest如果它不是可選的,可能也會這樣做。
沒有評論也不content是真正的評論:
class Comment < ApplicationRecord
belongs_to :inquest
belongs_to :user
validates :content, presence: true
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/460251.html
