Active Record 結果
此類別封裝了在任何資料庫連接配接器上呼叫 #exec_query 後返回的結果。例如:
result = ActiveRecord::Base.lease_connection.exec_query('SELECT id, title, body FROM posts')
result # => #<ActiveRecord::Result:0xdeadbeef>
# Get the column names of the result:
result.columns
# => ["id", "title", "body"]
# Get the record values of the result:
result.rows
# => [[1, "title_1", "body_1"],
[2, "title_2", "body_2"],
...
]
# Get an array of hashes representing the result (column => value):
result.to_a
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
{"id" => 2, "title" => "title_2", "body" => "body_2"},
...
]
# ActiveRecord::Result also includes Enumerable.
result.each do |row|
puts row['title'] + " " + row['body']
end
命名空間
方法
- #
- E
- I
- L
- N
- T
已包含模組
屬性
[R] | column_types | |
[R] | columns | |
[R] | rows |
類別公開方法
new(columns, rows, column_types = nil) 連結
來源:顯示 | 在 GitHub 上
# File activerecord/lib/active_record/result.rb, line 102 def initialize(columns, rows, column_types = nil) # We freeze the strings to prevent them getting duped when # used as keys in ActiveRecord::Base's @attributes hash @columns = columns.each(&:-@).freeze @rows = rows @hash_rows = nil @column_types = column_types || EMPTY_HASH @column_indexes = nil end
實體公開方法
[](idx) 連結
來源:顯示 | 在 GitHub 上
# File activerecord/lib/active_record/result.rb, line 148 def [](idx) hash_rows[idx] end
each(&block) 連結
針對 row 集合中的每個元素呼叫給定的區塊一次,將 row 作為參數傳遞。每個 row 是一個類似雜湊的唯讀物件。
要取得真正的雜湊,請使用 .to_a.each
。
如果未提供區塊,則返回一個 Enumerator
。
來源:顯示 | 在 GitHub 上
# File activerecord/lib/active_record/result.rb, line 128 def each(&block) if block_given? hash_rows.each(&block) else hash_rows.to_enum { @rows.size } end end
empty?() 連結
如果沒有記錄,則返回 true,否則返回 false。
來源:顯示 | 在 GitHub 上
# File activerecord/lib/active_record/result.rb, line 137 def empty? rows.empty? end
includes_column?(name) 連結
如果此結果集包含名為 name
的欄位,則返回 true
來源:顯示 | 在 GitHub 上
# File activerecord/lib/active_record/result.rb, line 113 def includes_column?(name) @columns.include? name end
initialize_copy(other) 連結
來源:顯示 | 在 GitHub 上
# File activerecord/lib/active_record/result.rb, line 191 def initialize_copy(other) @rows = rows.dup @column_types = column_types.dup @hash_rows = nil end
last(n = nil) 連結
返回 rows 集合中的最後一筆記錄。
來源:顯示 | 在 GitHub 上
# File activerecord/lib/active_record/result.rb, line 153 def last(n = nil) n ? hash_rows.last(n) : hash_rows.last end
length() 連結
返回 rows 陣列中的元素個數。
來源:顯示 | 在 GitHub 上
# File activerecord/lib/active_record/result.rb, line 118 def length @rows.length end
to_ary() 連結
返回一個雜湊陣列,表示每行記錄。
也稱為:to_a
來源:顯示 | 在 GitHub 上
# File activerecord/lib/active_record/result.rb, line 142 def to_ary hash_rows end