how do I associate one model twice to another

后端 未结 1 1714
青春惊慌失措
青春惊慌失措 2021-02-06 06:52

Hi im making a small site to help me and friends learn languages. Typical use:

Adam is english but is learning japanese. Adam can practice his japanese by writing and

相关标签:
1条回答
  • 2021-02-06 07:11

    Yeah, you're right. The association between User and Language is twofold. It's quite easy to model this situation using Rails:

    class Language < AR::Base
      has_many :native_speakers, :class_name => "User", :foreign_key => "native_language_id"
      has_many :second_language_speakers, :class_name => "User", :foreign_key => "second_language_id"
      has_many :articles
    end
    
    class User < AR::Base
      # we expect the users table to have native_language_id and second_language_id columns
      belongs_to :native_language, :class_name => "Language"
      belongs_to :second_language, :class_name => "Language"
      has_many :second_language_articles, :through => :second_language, :source => :articles
      has_many :native_language_articles, :through => :native_language, :source => :articles
    end
    
    class Article < AR::Base
      belongs_to :language
    end
    

    Something like that should work.

    0 讨论(0)
提交回复
热议问题