How do I create an ActiveRecord relationship to an

2020-07-13 07:55发布

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?

3条回答
啃猪蹄的小仙女
2楼-- · 2020-07-13 08:09

I suppose one possibility for #1, assuming I can get any of it working, is to do this:

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

But it loses a lot of what has_many offers.

查看更多
\"骚年 ilove
3楼-- · 2020-07-13 08:14

I think a better solution would be making a method that returns a scope.

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
查看更多
够拽才男人
4楼-- · 2020-07-13 08:25

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.

查看更多
登录 后发表回答