5

假设我正在为已经拥有 People 应用程序的出版公司编写图书馆应用程序。

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

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

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

class Article < ActiveRecord::Base
  belongs_to :person, :as => :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工作吗?belongs_to考虑到没有ActiveRecord也没有后备表,甚至会起作用吗?

4

3 回答 3

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

但它失去了很多东西has_many

于 2008-10-08T16:19:31.313 回答
2

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

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

于 2009-07-26T01:08:31.590 回答
0

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

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
于 2010-08-17T22:37:30.923 回答