多态关联属于User

时间:2015-02-24 19:23:46

标签: ruby-on-rails model-view-controller rails-activerecord polymorphic-associations

我有一个评论模型,这是一个与状态和照片有关的多态关联。如何创建此多态关联也属于用户,以便当用户在状态或照片下创建评论时,它还会收到current_user ID?

这就是我现在所拥有的 -

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

2 个答案:

答案 0 :(得分: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  

答案 1 :(得分:0)

有点hacky但我发现了一个解决方法。所以在我的CommentsController中我这样做了:

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。