我认为还有另一种可能。
首先是您问题的 MWE(最小工作示例):
require 'sequel'
Sequel.extension :pretty_table #Sequel::PrettyTable.print()/Sequel::PrettyTable.string()
DB = Sequel.sqlite
DB.create_table(:wishlists){
primary_key :id
String :listname
}
DB.create_table(:items){
primary_key :id
String :descr
}
DB.create_table(:items_wishlists){
primary_key :id
foreign_key :wishlist_id, :wishlists
foreign_key :item_id, :items
add_column :facebook_id, type: :nvarchar
}
class Item < Sequel::Model
many_to_many :wishlists
end
class Wishlist < Sequel::Model
many_to_many :items
end
w1 = Wishlist.create(listname: 'list1')
w1.add_item(Item.create(descr: 'item 1'))
#w1.add_item(Item.create(descr: 'item 2'), facebook_id: 'fb2') ##<- This does not work
#Sequel::PrettyTable.print(Wishlist)
#Sequel::PrettyTable.print(Item)
Sequel::PrettyTable.print(DB[:items_wishlists])
要允许ad_item
使用参数 ( Wishlist#add_item(Item.create(descr: 'item 2'), facebook_id: 'fb2')
),您必须定义一个adder
,如下例所示:
require 'sequel'
Sequel.extension :pretty_table
Sequel::PrettyTable.print()/Sequel::PrettyTable.string()
DB = Sequel.sqlite
DB.create_table(:wishlists){
primary_key :id
String :listname
}
DB.create_table(:items){
primary_key :id
String :descr
}
DB.create_table(:items_wishlists){
primary_key :id
foreign_key :wishlist_id, :wishlists
foreign_key :item_id, :items
add_column :facebook_id, type: :nvarchar
}
class Item < Sequel::Model
#~ many_to_many :wishlists
end
class Wishlist < Sequel::Model
many_to_many :items,
join_table: :items_wishlists, class: Item,
left_key: :wishlist_id, right_key: :item_id,
adder: (lambda do |item, facebook_id: nil|
self.db[:items_wishlists].insert(wishlist_id: self.id, item_id: item.id, facebook_id: facebook_id)
end)
end
w1 = Wishlist.create(listname: 'list1')
w1.add_item(Item.create(descr: 'item 1'))
w1.add_item(Item.create(descr: 'item 2'), facebook_id: 'fb2')
Sequel::PrettyTable.print(DB[:items_wishlists])
结果:
+-----------+--+-------+-----------+
|facebook_id|id|item_id|wishlist_id|
+-----------+--+-------+-----------+
| | 1| 1| 1|
|fb2 | 2| 2| 1|
+-----------+--+-------+-----------+
但下一个问题将在稍后出现:
随着w1.items
您获得项目列表,但您无权访问参数。(至少到目前为止我没有发现任何方法。我仍在研究,但我希望我需要一个连接表的模型(参见 Jeremys 的建议))