Module | Sequel::Model::DatasetMethods |
In: |
lib/sequel/model/base.rb
|
Dataset methods are methods that the model class extends its dataset with in the call to set_dataset.
model | [RW] |
The model class associated with this dataset
Artist.dataset.model # => Artist |
Assume if a single integer is given that it is a lookup by primary key, and call with_pk with the argument.
Artist.dataset[1] # SELECT * FROM artists WHERE (id = 1) LIMIT 1
# File lib/sequel/model/base.rb, line 1562 1562: def [](*args) 1563: if args.length == 1 && (i = args.at(0)) && i.is_a?(Integer) 1564: with_pk(i) 1565: else 1566: super 1567: end 1568: end
Destroy each row in the dataset by instantiating it and then calling destroy on the resulting model object. This isn‘t as fast as deleting the dataset, which does a single SQL call, but this runs any destroy hooks on each object in the dataset.
Artist.dataset.destroy # DELETE FROM artists WHERE (id = 1) # DELETE FROM artists WHERE (id = 2) # ...
# File lib/sequel/model/base.rb, line 1579 1579: def destroy 1580: pr = proc{all{|r| r.destroy}.length} 1581: model.use_transactions ? @db.transaction(&pr) : pr.call 1582: end
This allows you to call to_hash without any arguments, which will result in a hash with the primary key value being the key and the model object being the value.
Artist.dataset.to_hash # SELECT * FROM artists # => {1=>#<Artist {:id=>1, ...}>, # 2=>#<Artist {:id=>2, ...}>, # ...}
# File lib/sequel/model/base.rb, line 1592 1592: def to_hash(key_column=nil, value_column=nil) 1593: if key_column 1594: super 1595: else 1596: raise(Sequel::Error, "No primary key for model") unless model and pk = model.primary_key 1597: super(pk, value_column) 1598: end 1599: end
Given a primary key value, return the first record in the dataset with that primary key value.
# Single primary key Artist.dataset.with_pk(1) # SELECT * FROM artists WHERE (id = 1) LIMIT 1 # Composite primary key Artist.dataset.with_pk([1, 2]) # SELECT * FROM artists # WHERE ((id1 = 1) AND (id2 = 2)) LIMIT 1
# File lib/sequel/model/base.rb, line 1610 1610: def with_pk(pk) 1611: case primary_key = model.primary_key 1612: when Array 1613: raise(Error, "single primary key given (#{pk.inspect}) when a composite primary key is expected (#{primary_key.inspect})") unless pk.is_a?(Array) 1614: raise(Error, "composite primary key given (#{pk.inspect}) does not match composite primary key length (#{primary_key.inspect})") if pk.length != primary_key.length 1615: first(primary_key.zip(pk)) 1616: else 1617: raise(Error, "composite primary key given (#{pk.inspect}) when a single primary key is expected (#{primary_key.inspect})") if pk.is_a?(Array) 1618: first(primary_key=>pk) 1619: end 1620: end