Class: ActiveRecord::Relation
- Defined in:
- lib/jun/active_record/relation.rb
Instance Method Summary collapse
- #each(&block) ⇒ Object
- #first ⇒ Object
-
#initialize(klass) ⇒ Relation
constructor
A new instance of Relation.
- #records ⇒ Object (also: #to_a)
- #to_sql ⇒ Object
- #where(condition) ⇒ Object
- #where!(condition) ⇒ Object
Constructor Details
#initialize(klass) ⇒ Relation
Returns a new instance of Relation.
5 6 7 8 |
# File 'lib/jun/active_record/relation.rb', line 5 def initialize(klass) @klass = klass @where_clauses = [] end |
Instance Method Details
#each(&block) ⇒ Object
38 39 40 |
# File 'lib/jun/active_record/relation.rb', line 38 def each(&block) records.each(&block) end |
#first ⇒ Object
34 35 36 |
# File 'lib/jun/active_record/relation.rb', line 34 def first records.first end |
#records ⇒ Object Also known as: to_a
28 29 30 |
# File 'lib/jun/active_record/relation.rb', line 28 def records @records ||= @klass.find_by_sql(to_sql) end |
#to_sql ⇒ Object
21 22 23 24 25 26 |
# File 'lib/jun/active_record/relation.rb', line 21 def to_sql sql = "SELECT * FROM #{@klass.table_name}" sql += " WHERE #{@where_clauses.join(" AND ")}" if @where_clauses.any? sql end |
#where(condition) ⇒ Object
17 18 19 |
# File 'lib/jun/active_record/relation.rb', line 17 def where(condition) clone.where!(condition) end |
#where!(condition) ⇒ Object
10 11 12 13 14 15 |
# File 'lib/jun/active_record/relation.rb', line 10 def where!(condition) clause = condition.is_a?(String) ? condition : condition.map { |k, v| "#{k} = #{v}" }.join(" AND ") @where_clauses << clause self end |