【问题标题】:How do I create an ActiveRecord relationship to an ActiveResource object?如何创建与 ActiveResource 对象的 ActiveRecord 关系?
【发布时间】:2008-10-08 16:16:54
【问题描述】:

假设我正在为一家已经拥有 People 应用程序的出版公司编写图书馆应用程序。

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

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

现在我想为每个Person 存储Articles:

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

我想我的数据库中有下表:

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

author_id 不完全是外键,因为我没有 People 表。这留下了几个问题:

  1. 我如何告诉我的Person ActiveResource 对象它has_many Articles

  2. Articles.find(:first).author 会起作用吗?考虑到没有ActiveRecord 也没有后备表,belongs_to 还能工作吗?

【问题讨论】:

    标签: ruby-on-rails activerecord activeresource


    【解决方案1】:

    我认为 #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 提供的很多

    【讨论】:

      【解决方案2】:

      正如您所指出的,您放弃了很多,因为 ActiveResource 没有 ActiveRecord 所具有的关联。

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

      【讨论】:

        【解决方案3】:

        我认为更好的解决方案是创建一个返回范围的方法。

        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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多