假设我正在为已经拥有People应用程序的出版公司编写一个图书馆应用程序。
所以在我的图书馆应用程序中我有
class Person < ActiveResource::Base
self.site = "http://api.people.mypublisher.com/"
end
现在我想为每个Article
存储Person
:
class Article < ActiveRecord::Base
belongs_to :person, :as => :author
end
我想我的数据库中有以下表格:
Articles
id (PK) | title (string) | body (text) | author_id (integer)
author_id
不完全是外键,因为我没有人员表。这留下了几个问题:
如何告诉我的Person
ActiveResource
对象has_many
Articles
?
Articles.find(:first).author
会有效吗?鉴于没有belongs_to
且没有支持表,ActiveRecord
是否会工作?
答案 0 :(得分: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
提供的很多。
答案 1 :(得分:2)
正如您所指出的,您放弃了很多,因为ActiveResource在ActiveRecord的意义上没有关联。
您已经找到问题#1的答案。对于问题#2,当您配置与ActiveResource模型的“belongs_to”关联时,您的ActiveRecord模型文章应该表现得很好。那就是Aritcle.find(:first).author应该返回你想要的person对象。
答案 2 :(得分: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