【问题标题】:Belongs to many association?属于多协会?
【发布时间】:2016-09-13 21:42:47
【问题描述】:

我想这是一个非常概念性的问题。我正在查看通过 Rails 可用的可能关联,但似乎无法围绕如何构建“belongs_to_many”和“has_many”关联。

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

我能找到的最接近的是“has_many_and_belongs_to”关联,但根据我找到的所有示例,它并不完全准确。

同样,根据文档,“属于”和“拥有多个”关联是指一对多。

是否存在与我可以使用的多种风格或某种模型结构相匹配的关联?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    你需要使用任何一个

    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
      

    【讨论】:

      猜你喜欢
      • 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
      相关资源
      最近更新 更多