我有一个简单的多态评论模型,定义如下:
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