我有一個評論模型,這是一個多態關聯,涉及狀態和照片。如何創建這個多態關聯也屬於一個用戶,以便當用戶在狀態或照片下創建註釋時,它也將接收current_user id?多態關聯屬於用戶
這是我作爲有NOW-
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
belongs_to :user
end
class User < ActiveRecord::Base
has_many :comments
end
class Status < ActiveRecord::Base
has_many :comments, as: :commentable
end
class Photo < ActiveRecord::Base
has_many :comments, as: :commentable
end
只是重申,我怎麼可以創建一個用戶評論,但也有它的狀態下或照片?它將需要user_id。
這是我遇到麻煩的地方 - 我應該如何設置?
def create
@comment = @commentable.comments.new(comments_params)
if @comment.save
redirect_to @commentable, notice: "Comment created"
else
render :new
end
end
這個是非常古老的,我已經回答了。您可以從www.xyzpub.com/en/ruby-on-rails/3.2/activerecord_polymorphic.html中很好地理解 – Sontya 2015-02-24 23:35:02