【发布时间】:2015-02-24 19:23:46
【问题描述】:
我有一个 cmets 模型,它是一个涉及状态和照片的多态关联。如何创建此多态关联以也属于用户,以便当用户在状态或照片下创建评论时,它也会收到 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
【问题讨论】:
标签: ruby-on-rails model-view-controller rails-activerecord polymorphic-associations