【发布时间】:2014-04-15 15:54:27
【问题描述】:
我正在努力实现多态 cmets(这些可以应用于站点上的几乎任何用户内容,并且不限于 Article 实例。创建评论时,我需要确定它属于哪个 commentable我在这个主题上找到的大部分文章都建议我在下面的代码中使用find_commentable 中指定的模式,但这种方法并没有让我觉得非常优雅——似乎应该有一种直截了当的方法来明确指定正在为其创建新评论的commentable,无需遍历params 集合,也无需字符串匹配。有更好的方法吗?
换句话说,在commentable → comment 关联的上下文中,是否有更好的方法从comment 控制器访问commentable 对象?在我们还没有 @comment 对象可以使用的情况下,它仍然可以使用 create 方法吗?
我的模型设置如下:
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
end
class Article < ActiveRecord::Base
has_many :comments, :as => :commentable, dependent: :destroy
end
class CommentsController < ApplicationController
def create
@commentable = find_commentable
@comment = @commentable.comments.build(comment_params)
if @comment.save
redirect_to :back
else
render :action => 'new'
end
end
def index
@commentable = find_commentable
@comments = @commentable.comments
end
private
def comment_params
params.require(:comment).permit(:body)
end
def find_commentable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
end
end
谢谢!
【问题讨论】:
-
你可以重新定义你的 find_commentable 方法:
params[:commentable_type].constantize.find_by_id(params[:commentable_id]])
标签: ruby-on-rails activerecord ruby-on-rails-4