0

我有一個評論模型,這是一個多態關聯,涉及狀態和照片。如何創建這個多態關聯也屬於一個用戶,以便當用戶在狀態或照片下創建註釋時,它也將接收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 

回答

0

這是一個有點哈克但我找到了一個解決方法。所以在我的評論控制器我做到了這一點:

def create 
    new_params = comments_params 
    new_params[:user_id] = current_user.id 
    @comment = @commentable.comments.build(new_params) 

    if @comment.save 
     redirect_to @commentable, notice: "Comment created" 
    else 
     render :new 
    end 
    end 

放置user_id這是我所需要的。

+0

這個是非常古老的,我已經回答了。您可以從www.xyzpub.com/en/ruby-on-rails/3.2/activerecord_polymorphic.html中很好地理解 – Sontya 2015-02-24 23:35:02

0

試試這個

class Comment < ActiveRecord::Base 
    belongs_to :likable, :polymorphic => true 
    belongs_to :commentable, :polymorphic => true 
    belongs_to: user 

class User < ActiveRecord::Base 
    has_many :statuses, :as => :likable 
    has_many :photos, :as => :commentable 
    has_many :comments 


class Status < ActiveRecord::Base 
    has_many :comments, :as => :likable, :dependent => :destroy 


class Photos < ActiveRecord::Base 
    has_many :comments, :as => :commentable, :dependent => :destroy 
+0

你能解釋一下嗎? – 2015-02-24 20:33:07

+0

如果你說'@ comment.likable'應該返回狀態,'@ comment.commentable'應該返回照片,'@ user.photos','@ user.statuses'應該給'照片'和'狀態'爲那個用戶 – Sontya 2015-02-24 20:46:05

+0

你應該可以創建'@comment = @ status.comments.new(comments_params)'或'@comment = @ photo.comments.new(comments_params)' – Sontya 2015-02-24 20:52:20