在ActiveResource对象中使用has_many方法与本地ActiveRecord对象相关联?

时间:2014-06-10 01:32:36

标签: ruby ruby-on-rails-3 activeresource

我想使用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,那么我应该如何解决这个问题?

1 个答案:

答案 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