如何创建一个ActiveRecord关系到的ActiveResource对象? [英] How do I create an ActiveRecord relationship to an ActiveResource object?

查看:166
本文介绍了如何创建一个ActiveRecord关系到的ActiveResource对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我正在写一个图书馆申请谁已经有一个人申请一个出版公司。

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

 类Person<的ActiveResource ::基地
  self.site =htt​​p://api.people.mypublisher.com/
结束
 

现在我想要存储文章 S代表每个

 类文章<的ActiveRecord :: Base的
  belongs_to的:人:为=> :作者
结束
 

我想我有如下表在我的数据库:

 文章
ID(PK)|标题(字符串)|主体(文本)| AUTHOR_ID(整数)
 

AUTHOR_ID 是不完全外键,因为我没有一个人桌。剩下几个问题:

  1. 我怎么告诉我的 的ActiveResource 对象,它的has_many 文章

  2. 威尔 Articles.find(:第一).author 工作?请问 belongs_to的甚至工作因为没有的ActiveRecord 并没有支持表?

解决方案

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

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

Let's say I'm writing a Library application for a publishing company who already has a People application.

So in my Library application I have

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

and now I want to store Articles for each Person:

class Article < ActiveRecord::Base
  belongs_to :person, :as => :author
end

I imagine I'd have the following table in my database:

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

author_id isn't exactly a Foreign-Key, since I don't have a People table. That leaves several questions:

  1. how do I tell my Person ActiveResource object that it has_many Articles?

  2. Will Articles.find(:first).author work? Will belongs_to even work given that there's no ActiveRecord and no backing table?

解决方案

As you point out, you are giving up a lot because ActiveResource does not have associations in the sense that ActiveRecord does.

You have already found the answer to question #1. As for question #2, your ActiveRecord model Article should behave just fine when configured with a "belongs_to" association to an ActiveResource model. That is Aritcle.find(:first).author should return the person object you want.

这篇关于如何创建一个ActiveRecord关系到的ActiveResource对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆