次のように定義された単純なポリモーフィックコメントモデルがあります。
class Comment < ActiveRecord::Base
include Rails.application.routes.url_helpers
if Rails.env.production?
default_url_options[:host] = "www.livesite.org"
else
default_url_options[:host] = "livesite.dev"
end
attr_accessible :content
attr_accessible :commentable_id, :commentable_type
belongs_to :commentable, polymorphic: true
belongs_to :user
validates_presence_of :content
after_create :subscribe_to, :notify_subscribers
private
def subscribe_to
commentable.rdb[:subscribers].sadd user_id
end
def notify_subscribers
subscriber_ids = commentable.rdb[:subscribers].smembers.to_a
subscriber_ids.delete user_id.to_s
# remove the author's id from the array
subscribers = User.where(id: subscriber_ids)
subscribers.each do |subscriber|
subscriber.notifications.create(
content: "<a href='#{ user_url(user) }'>#{user.name}</a> commented about <a href='#{ polymorphic_url(commentable) }'>#{commentable.name}</a>",
read: false,
notifyable: commentable
)
end
end
end
Redis のちょっとした魔法を使って、特定のコメント可能なサブスクライバーを多数作成していることがわかりますが、私の質問は、polymorphic_url
ここでモデルの一部を抽象化するにはどうすればよいかということです。モデルレベルでそれを持っているのは奇妙に思えます。より良いアプローチはありますか?ここにあるということは、 を含める必要があることを意味url_helpers
し、Capybara と連携して実際の palava をテストしています。
参考までに、Notification.rb は次のとおりです。
class Notification < ActiveRecord::Base
attr_accessible :subject, :read, :user_id, :notifyable
belongs_to :user
belongs_to :notifyable, polymorphic: true
default_scope order('created_at DESC')
end