我在构建适当的模型,关联和查询以下场景时遇到问题,然后使用Sequel with Ruby将结果作为JSON返回。
数据库结构___
您可以创建图书清单。每个图书馆都有书籍。定义如下:
db.create_table(:books) do
primary_key :id
String :name
String :author
DateTime :created
end
db.create_table(:libraries) do
primary_key :id
String :name
String :city
String :state
DateTime :created
end
db.create_table(:libraries_books) do
Integer :library_id
Integer :book_id
primary_key [:library_id, :book_id]
end
class Library < Sequel::Model(:libraries)
many_to_many :libraries_books, :left_key=>:library_id, :right_key=>:book_id, :join_table=>:libraries_books
one_to_many :libraries_books, :key=>:library_id
end
class LibraryBook < Sequel::Model(:libraries_books)
many_to_one :libraries
many_to_one :books
end
我正在尝试确定访问给定库的所有书名的正确方法。我最初试图遵循Sequel Associations指南,但是无法弄清楚如何使用LibraryBook和关联来获取库的所有书籍并加入Book模型以获得正确的列。
在遇到所描述的一些方法后,我试图创建我自己的查询:
LibraryBook.select(:books.*)
.join_table(:inner, :libraries, :id => :library_id)
.join_table(:inner, :books, :id => :book_id)
.where(:library_id => 1)
这似乎让我部分在那里。但是,当我使用序列化扩展时,我在转换结果时出错:
undefined method `book_id' for #<LibraryGame:0x007fa9e904b470>
对此提供的任何见解都会非常有用!
答案 0 :(得分:3)
尝试以下方法:
db.create_table(:books) do
primary_key :id
String :name
String :author
DateTime :created
end
db.create_table(:libraries) do
primary_key :id
String :name
String :city
String :state
DateTime :created
end
db.create_table(:books_libraries) do
foreign_key :library_id, :libraries, key: :id
foreign_key :book_id, :books, key: :id, index: true
primary_key [:library_id, :book_id]
end
class Library < Sequel::Model
many_to_many :books
end
class Book < Sequel::Model
many_to_many :libraries
end
注意将libraries_books
表重命名为books_libraries
,并使用foreign_key指令进行参照完整性。公约应该允许事情正常运作。
Library[7].books # returns all books for library '7'
或者:
Book.where(libraries: Library[7])
或多个库:
Book.where(libraries: Library.where(id: [3,7,9]))
如果续集无法对图书馆/图书馆进行变形,那么您可能需要添加自己的inflection rule,例如:
Sequel.inflections do |inflect|
inflect.irregular 'Library', 'Libraries'
end