Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 属于多个协会?_Ruby On Rails - Fatal编程技术网

Ruby on rails 属于多个协会?

Ruby on rails 属于多个协会?,ruby-on-rails,Ruby On Rails,我想这是一个相当概念化的问题。我正在查看Rails中可能存在的关联,但似乎无法理解如何构建“属于”和“拥有”关联 具体来说,我希望读者有很多书,每本书都属于很多读者 我能找到的最接近的关联是“has_many_and_belient_to”,但根据我找到的所有示例,它并不完全准确 同样,根据文档,“属于”和“有多个”关联的意思是一对多 是否有一个关联可以匹配属于多种样式或某种我可以使用的模型结构 您需要使用 或 class Book < ActiveRecord::Base h

我想这是一个相当概念化的问题。我正在查看Rails中可能存在的关联,但似乎无法理解如何构建“属于”和“拥有”关联

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

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

同样,根据文档,“属于”和“有多个”关联的意思是一对多


是否有一个关联可以匹配属于多种样式或某种我可以使用的模型结构

您需要使用

  • class Book < ActiveRecord::Base
      has_and_belongs_to_many :readers
    end
    
    class Reader < ActiveRecord::Base
      has_and_belongs_to_many :books
    end
    
    rails g migration CreateJoinTableBooksReaders books readers
    
    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
    
    rails g model BookReader book:references reader:references