多态关联属于用户
polymorphic association belongs to User
我有一个评论模型,它是一个涉及状态和照片的多态关联。我如何创建这个多态关联也属于一个用户,以便当用户在状态或照片下创建评论时它也会收到 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
试试这个
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
这有点老套,但我找到了解决方法。所以在我的 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。
我有一个评论模型,它是一个涉及状态和照片的多态关联。我如何创建这个多态关联也属于一个用户,以便当用户在状态或照片下创建评论时它也会收到 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
试试这个
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
这有点老套,但我找到了解决方法。所以在我的 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。