Rails has_many through,外键和源代码问题

时间:2014-06-15 17:12:06

标签: ruby-on-rails

User有许多订阅者和许多发布者,两者都是用户:

class User < ActiveRecord::Base
    has_many :relationships, :foreign_key => "subscriber_id"
    has_many :subscribers, :through => :relationships, :source => :subscriber

    has_many :inverse_relationships, :class_name => "Relationship", :foreign_key => "publisher_id"
    has_many :publishers, :through => :inverse_relationships, :source => :publisher

    def subscribe_to(publisher)
        self.relationships.create!(publisher_id: publisher.id, subscriber_id: id)
    end
end

class Relationship < ActiveRecord::Base
    belongs_to :subscriber, :class_name => "User"
    belongs_to :publisher, :class_name => "User"
end

用户订阅的用户的发布者。

但是,如果我执行john.subscribe_to(a_publisher),然后尝试puts john.publishers,我会返回一个空数组。

我来回地随意改变外键和来源,希望它最终会起作用,但有些东西是关闭的。源和外键应该在这里?

更新

以下是我的工作:

class User < ActiveRecord::Base
    has_many :relationships, :foreign_key => "publisher_id"
    has_many :subscribers, :through => :relationships, :source => :subscriber

    has_many :inverse_relationships, :foreign_key => "subscriber_id", :class_name => "Relationship"
    has_many :publishers, :through => :inverse_relationships, :source => :publisher

    def subscribe_to(publisher)
        publisher.relationships.create!(subscriber_id: id)
    end
end

首先,我为两者切换了外键。第二,这是我不理解的部分,我改变了

self.relationships.create!(publisher_id: publisher.id)

publisher.relationships.create!(subscriber_id: id)

它有效。出于某种原因,它没有相反的工作方式。任何人都可以解释原因吗?

1 个答案:

答案 0 :(得分:0)

您的协会似乎很奇怪。你应该这样试试:

 has_many :subscribers, :through => :relationships, :class_name => 'User'

并致电:

 john.subscribers.create(a_publisher)

您所说的subscriber只是User。我认为你的问题来自这里。

也许您可以尝试::source => :user