属于许多协会?

时间:2016-09-13 13:17:47

标签: ruby-on-rails

我想这是一个非常概念性的问题。我正在通过Rails查看可能的关联,但似乎无法理解如何建立一个" belongs_to_many"和" has_many"协会。

具体来说,我希望读者有很多书,每本书都属于很多读者。

我能找到的最近的是" has_many_and_belongs_to"关联,但基于我发现的所有例子,它并不完全准确。

同样,根据文档,"属于"并且"有很多"协会意味着一对多。

是否有可用的关联符合属于我可以使用的多种样式或某种模型结构?

1 个答案:

答案 0 :(得分:2)

你需要使用

  1. has_and_belongs_to_many

    class Book < ActiveRecord::Base
      has_and_belongs_to_many :readers
    end
    
    class Reader < ActiveRecord::Base
      has_and_belongs_to_many :books
    end
    

    使用这种方法,您需要创建一个名为books_readers

    的连接表
    rails g migration CreateJoinTableBooksReaders books readers
    
    1. has_many :through

      class Book < ActiveRecord::Base
        has_many :book_readers
        has_many :readers, through: :book_readers
      end
      
      class Reader < ActiveRecord::Base
        has_many :book_readers
        has_many :books, through: :book_readers
      end
      
      class BookReader < ActiveRecord::Base
        belongs_to :reader
        belongs_to :book
      end
      

      使用这种方法,您需要创建一个新模型BookReader

      rails g model BookReader book:references reader:references