如何创建与ActiveResource对象的ActiveRecord关系?

假设我正在为已经拥有People应用程序的出版公司编写一个Library应用程序。

所以在我的图书馆应用程序中我有

class Person < ActiveResource::Base self.site = "http://api.people.mypublisher.com/" end 

现在我想为每个Person存储Article

 class Article  :author end 

我想我的数据库中有以下表格:

 Articles id (PK) | title (string) | body (text) | author_id (integer) 

author_id不完全是外键,因为我没有People表。 这留下了几个问题:

  1. 如何告诉我的Person ActiveResource对象它has_many Articles

  2. Articles.find(:first).author工作吗? 鉴于没有ActiveRecord和没有支持表,will belongs_to会工作?

正如您所指出的,您放弃了很多,因为ActiveResource在ActiveRecord的意义上没有关联。

您已经找到问题#1的答案。 对于问题#2,当您配置与ActiveResource模型的“belongs_to”关联时,您的ActiveRecord模型文章应该表现得很好。 那就是Aritcle.find(:first).author应该返回你想要的person对象。

我认为#1的一种可能性,假设我可以使其中的任何一个工作,就是这样做:

 class Person < ActiveResource::Base self.site = "http://api.people.mypublisher.com/" def articles Article.find(:all, :conditions => { :person_id => self.id }) end def add_article(article) article.person_id = self.id end end 

但它失去了很多 has_many提供的东西。

我认为更好的解决方案是制作一个返回范围的方法。

 class Person < ActiveResource::Base self.site = .. . def articles Article.for_person(self.id) end end class Article < ActiveRecord::Base named_scope :for_person, lambda { |pid| { :conditions => { :person_id => pid }}} end