如何创建与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表。 这留下了几个问题:
-
如何告诉我的
Person
ActiveResource
对象它has_many
Articles
? -
Articles.find(:first).author
工作吗? 鉴于没有ActiveRecord
和没有支持表,willbelongs_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
- schema.rb索引与单个迁移索引不同
- 如何在Postgres中进行查询以按月创建分组记录? (:created_at datetime列)
- 如何在rails中保存ActiveRecord模型后获取id值
- Rails模型“before_filter”?
- Ruby on Rails Active Record RANDOM()在循环中始终相同
- 使用accepts_nested_attributes_for将现有has_many记录添加到新记录
- 在查询随机简单查询时丢失与MySQL服务器的连接
- Ruby on Rails:有没有办法从数据库中提取项目并按指定顺序返回它们?
- Rails ActiveRecord – 在多个属性上搜索