我正在嘗試學習 Ruby on Rails,但我有點堅持使用 associaton。我的專案是用三個表創建一個簡單的博客。用戶、帖子和評論。
據我了解,在將幾個表與外鍵關聯后,rails 會自動找到 user_id 和 post_id。但是每次我嘗試建立評論時,user_id 都是 nil。
這是我的模型:
class User < ApplicationRecord
has_many :posts
has_many :comments
validates :name, presence: true, length: { minimum: 5 }, uniqueness: true
validates :password, presence: true, length: { minimum: 5 }
end
class Post < ApplicationRecord
belongs_to :user
has_many :comments
validates :title, presence: true
validates :body, presence: true, length: {minimum: 10}
end
class Comment < ApplicationRecord
belongs_to :post
belongs_to :user
validates :body, presence: true
validates :user_id, presence: true
validates :post_id, presence: true
end
這是我嘗試創建評論時的螢屏截圖:

如您所見,post_id 不是 nil,但 user_id 是 nil。
我嘗試手動輸入 user_id 并按預期作業。但我不知道如何使用自動 user_id 和 post_id 創建評論。
uj5u.com熱心網友回復:
據我了解,在將幾個表與外鍵關聯后,rails 會自動找到 user_id 和 post_id。但是每次我嘗試建立評論時,user_id 都是 nil。
這種假設是沒有道理的。Rails 不會自動分配您的關聯 - 它甚至應該如何知道您要將評論與哪個用戶/帖子關聯?
通常,您構建它的方式是使用嵌套路由:
resources :posts do
resources :comments,
only: [:create]
shallow: true
end
這將創建路由/posts/:post_id/comments,以便我們知道用戶想要評論哪個帖子 - 然后您將調整您的表單,使其發布到嵌套路由:
# app/views/comments/_form.html.erb
<%= form_with(model: [post, comment]) do |f| %>
# ...
<% end %>
# app/views/comments/_form.html.erb
<%= render partial: 'comments/form',
post: @post,
comment: @post.comments.new
獲取評論的用戶通常可以通過您的身份驗證系統從會話中獲取 - 在此示例中,authenticate_user!來自 Devise 的回呼將對用戶進行身份驗證,否則如果沒有用戶登錄,則重定向到登錄。
然后,您只需從請求正文(來自表單)和會話中的用戶分配白名單引數:
class CommentsController
before_action :authenticate_user!
# POST /posts/1/comments
def create
# This gets the post from our nested route
@post = Post.find(params[:post_id])
@comment = @post.comments.new(comment_params) do |c|
c.user = current_user
end
if @comment.save
redirect_to @post,
status: :created
notice: 'Comment created'
else
render :new, status: :unprocessable_entity
end
end
private
def comment_params
params.require(:comment)
.permit(:foo, :bar, :baz)
end
end
這通常是 Rails 初學者在“Blorgh”教程中最掙扎的部分,因為它介紹了“嵌入”在另一個資源中的資源及其視圖和幾個高級概念。如果你還沒有讀過,我真的會推薦Rails 入門指南。
uj5u.com熱心網友回復:
您可以創建如下評論:
user = User.find 2
post = user.posts.where(id: 2).first
comment = post.comments.build({comment_params}.merge(user_id: user.id))
希望這會幫助你。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/530363.html
