我有一個允許用戶評論帖子的應用程序。將用戶發表評論
rails generate model Comment commenter:string body:text post:references
我怎樣才能改變它,因此commenter
設置爲誰發佈評論
我有一個允許用戶評論帖子的應用程序。將用戶發表評論
rails generate model Comment commenter:string body:text post:references
我怎樣才能改變它,因此commenter
設置爲誰發佈評論
你應該檢查出的Rails指南協會用戶: http://guides.rubyonrails.org/association_basics.html。
您可能想要的是用戶模型與評論模型具有has_many belongs_to關係。
你的評論資源應該有一個:user_id是一個整數的列。在您的應用程序中,您可以通過致電@ comment.user來訪問這些信息。
你需要讓聯想:
rails generate model Comment author_id:integer body:text post:references
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :author, class_name: <User or whatever your user model is called>, foreign_key: :author_id
end
class User < ActiveRecord::Base
has_many :comments, foreign_key: :author_id
end
您還需要指定這個值,在創建新的註釋時:
#Comment controller? Hard to say how it is being saved from the code you posted. :P
def create
@comment = Comment.new(params[:comment])
@comment.user = current_user
if @comment.save
...
end
end
我終於找到了如何解決這個問題。
rails generate model Comment user_id:integer body:text listing:references
在\app\models\comments.rb
文件添加:user_id
到attr_accessible
然後隱藏屬性添加到評論表單:
<%= f.hidden_field :user_id, :value => current_user.id %>
然後使用<%= comment.user.id %>
和/或<%= comment.user.name %>
莫非你精確它略?你想讓你的評論模型返回寫評論的用戶嗎?如果是這樣,你想這個列是字符串還是你確定用戶ID? – BroiSatse
對不起,如果我沒有解釋得好。是的,我希望評論模型能夠返回發表評論的特定用戶。我不希望它是一個字符串(即...現在用戶可以輸入「評論者」名稱)我只希望用戶能夠輸入文本到正文中,並且他們的user_id與該關聯評論。 – Aluxzi