rails many to many self join

后端 未结 4 2053

could some one point me to the right direction:

I try to build a model for rails that build up the following:

ClassA -id

ClassA has a relation to

相关标签:
4条回答
  • 2020-11-30 04:42

    This post has a good working example: http://blog.hasmanythrough.com/2007/10/30/self-referential-has-many-through

    There is a related question here as well: Problem with self-referential has_many :through associations in Rails

    0 讨论(0)
  • 2020-11-30 04:45

    If it doesn't make too much sense to create another class to join the two, an alternative approach could be:

    class Word < ActiveRecord::Base 
      has_and_belongs_to_many :synonyms, class_name: "Word", 
                                         join_table: "word_synonyms",
                                         association_foreign_key: "synonym_id"
    end
    

    The join table would look like this:

    create_table :word_synonyms do |t|
      t.integer :word_id
      t.integer :synonym_id
    end
    
    0 讨论(0)
  • 2020-11-30 04:52

    Unfortunately whistler's answer might not be suitable in many cases. For instance, it doesn't work both ways. For instance, suppose you create a new word:

    word = Word.create(:word_name => 'tremble')
    ['shake', 'vibrate'].each { |syn| word.synonyms.create(:word_name => syn) }
    

    Now, if you do:

    word = Word.find_by_word_name('tremble')
    p word.synonyms # this would print out the Words with the word_name 'shake' and 'vibrate'.
    

    however, if you did it the other way around:

    word = Word.find_by_word_name('vibrate')
    
    p word.synonyms # this would print an empty association.
    

    This is saying the word 'vibrate' has NO synonyms.

    So basically, this method won't work both ways (i.e. vibrate is a synonym of tremble, and tremble is a synonym for vibrate)

    Edit: In a sense, you could use this approach, however, you would have to explicitly assign the synonyms for each word. So although you specified synonyms of tremble (which are 'vibrate' and 'shake'), you would have to still specify synonyms of 'shake' ('which are 'tremble' and 'vibrate') and 'vibrate' (which are 'tremble' and shake') as well.

    0 讨论(0)
  • 2020-11-30 04:59

    I'd use something like

    class Person < ActiveRecord::Base
       has_many :friendships, :foreign_key => "person_id", 
          :class_name => "Friendship"
    
       has_many :friends, :through => :friendships
    end
    
    class Friendship < ActiveRecord::Base
       belongs_to :person, :foreign_key => "person_id", :class_name => "Person"
       belongs_to :friend, :foreign_key => "friend_id", :class_name => "Person"  
    end
    

    And the tables would be like

    people: id; name; whatever-you-need    
    friendships: id; person_id; friend_id
    
    0 讨论(0)
提交回复
热议问题