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

Jam*_*sen 5 activerecord ruby-on-rails activeresource

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

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

class Person < ActiveResource::Base
  self.site = "http://api.people.mypublisher.com/"
end
Run Code Online (Sandbox Code Playgroud)

现在我想Article为每个存储s Person:

class Article < ActiveRecord::Base
  belongs_to :person, :as => :author
end
Run Code Online (Sandbox Code Playgroud)

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

Articles
id (PK) | title (string) | body (text) | author_id (integer)
Run Code Online (Sandbox Code Playgroud)

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

  1. 我怎么告诉我的Person ActiveResource对象呢has_many Articles

  2. Articles.find(:first).author工作吗?会belongs_to甚至工作因为没有ActiveRecord,没有支撑台?

Jam*_*sen 5

我认为#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
Run Code Online (Sandbox Code Playgroud)

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


cnk*_*cnk 2

正如您所指出的,您放弃了很多,因为 ActiveResource 没有 ActiveRecord 那样的关联。

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