我想使用ActiveResource
对象来映射服务中的Users
,但我想要与这些Users
我的代码看起来像这样:
user.rb:
class User < ActiveResource::Base
self.site = "http://my/api"
has_many :notifications, as: :notifiable, dependent: :destroy
attr_accessible :notifications_attributes
accepts_nested_attributes_for :notifications, allow_destroy: true
end
notification.rb:
class Notification < ActiveRecord::Base
belongs_to :notifiable, polymorphic: true
belongs_to :user
belongs_to :recipient, class_name: 'User'
end
如果ActiveResource
不支持has_many
,那么我应该如何解决这个问题?
答案 0 :(得分:3)
ActiveResource确实支持关联,但它们也应该是外部资源。所以在你的情况下它不适用。
我认为您的要求是合法的,并建议手动为它们构建方法。例如:
class User < ActiveResource::Base
self.site = "http://my/api"
def notifications
Notification.where(user_id: self.id)
end
end
class Notification < ActiveRecord::Base
belongs_to :notifiable, polymorphic: true
def user
User.find(self.user_id)
end
def recipient
User.find(self.recipient_id)
end
end