2014-02-05 35 views
0

我下面這個教程:添加用戶ID發表評論模型

http://guides.rubyonrails.org/getting_started.html#adding-a-second-model

它使用commentercomment用戶可以在其中添加名稱和消息時的作品,但我想用註釋關聯用戶ID(我已經有用戶)

它採用 rails generate model Comment commenter:string body:text post:references,但我想用一個用戶ID相關聯,以取代commenter:stringuser_id:integer?)。在之前的問題中,有人建議author_id:integer但它沒有工作。不知道從哪裏開始,似乎沒有關於這個主題的任何教程(我已經閱讀了關於關聯等的RoR幫助指南,但找不到用評論模型生成用戶ID的正確方法)

comments_controller.rb

def create 
@listing = Listing.find(params[:listing_id]) 
@comment = @listing.comments.create(params[:comment]) 
redirect_to listing_path(@listing) 
end 

回答

0

您可以生成註釋模式是這樣的:

軌生成模型評論用戶:引用正文:正文後:引用

您指定的references類型實際上將創建一個user_id:integer列,並增加了belongs_to聯想到Comment型號:

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

如果你想有一個Comment#commenter關聯參考用戶,而不是Comment#user,你可以在Comment模型把它定義如下:

class Comment < ActiveRecord::Base 
    belongs_to :commenter, class_name: 'User', foreign_key: 'user_id' 
    belongs_to :post 
end 
+0

我怎麼會得到一個具體的意見的用戶ID /職位/ 1頁,其中註釋和評論表單位於? (所以每個評論都有它旁邊的用戶標識)當我查看開發數據庫時,評論的user_id是空白的。如何在創建新評論時關聯用戶標識(我將發佈我的評論控制器) – Aluxzi

+0

這可能類似於:'@ post.comments.first.user_id'。或者你可以返回'User'實例:'@ post.comments.first.user'。 – fivedigit

+0

要爲用戶分配新評論,您需要獲取當前用戶實例,然後使用它創建評論:'@comment = @ listing.comments.create(params [:comment] .merge(user:user) )'。我假設你使用Rails 3.2或以下btw。 – fivedigit