How do I create an ActiveRecord relationship to an ActiveResource object?

点点圈 提交于 2019-12-04 07:33:54

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.

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.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!