RoR - More Active Record

Active Record Scope:

default_scope:   默认的检索方式

#Use unscoped to break out of the default 

class Hobby < ActiveRecord::Base 
    has_and_belongs_to_many :people 

    default_scope { order :name }
end 

Hobby.pluck :name 
# => ["Music","Programming"]

Hobby.unscoped.pluck :name 
# => ["Programming", "Music"]

#named scopes 
#scope :name, lambda

scope :ordered_by_age, -> {order age: :desc}
scope :starts_with, -> (starting_string) {where("first_name LIKE ?", "#{starting_string}%")}

Person.ordered_by_age.pluck :age 
# => [75,57,30,27,27] 

Person.ordered_by_age.starts_with("Jo").pluck :age, :first_name 
# => [[57,"Josh"],[27,"John"],[27,"John"]]

Person.ordered_by_age.limit(2).starts_with("Jo").pluck :age, :first_name 
# => [[57,"Josh"],[27,"John"]]

Scope 总是返回ActiveRecord::Relation

Validations:

数据总是要经过Validations才能存在数据库之中

#:presence and :uniqueness

presence: true 
# Make sure the field contains some data

uniqueness: true 
# 确保只有一个data

class Job < ActiveRecord::Base 
    belongs_to :person 
    has_one :salary_range 

    validates :title, :company, presence: true 
end 


#Other Common Validators 

:umericality 
# validates numeric input 

:length 
# validates value is a certain length 

:format 
# validates value complies with  some regular expression format 

:inclusion 
# validates value is inside specified range 

:exclusion 
# validates value is out of the specified range 

Writing your own validation:

class SalaryRange < ActiveRecord::Base 
    belongs_to :job 

    validate :min_is_less_than_max 

    def min_is_less_than_max 
        if min_salary > max_salary 
            errors.add(:min_salary, "cannot be greater than maximum salary!")
        end 
    end 
end 

N+1 Queries Issue and DB Transactions:

#solve for n+1 queries 

Person.includes(:personal_info).all.each { |p| puts p.personal_info.weight }

猜你喜欢

转载自www.cnblogs.com/vixennn/p/10707464.html