sábado, 23 de novembro de 2013

Ruby on Rails - Active Record Basics

Active Record Basics
=================

   Based on guides.rubyonrails.org
         
            It is the M from MVC

            Names convention
            Model/class      Table/Schema
                        Post                            posts              
                        LineItem                       line_items
                        Deer                            deer
                        Mouse                         mice

            Example of a class

                        class
                                    
                                   Product < ActiveRecord::Base
                                               self.table_name = "PRODUCT"   # Optional
                                               self.primary_key = "product_id" #Optional
                                   end

                        Result in DB
                                   CREATE TABLE products (
                                               id int(11)           NOT     NULL auto_increment,
                                               name varchar (255),
                                               PRIMARY KEY(id)
                                   );

            CRUD

            Create

                        user = User.create(name: "David", occupation: "Code Artist")
                        //with new object is created but not saved
                        user = User.new do |u|
                                    u.name = "David"
                                    u.occupation = "Code Artist"
                        end

            Read
                        More:
                          http://guides.rubyonrails.org/active_record_querying.html

                        # return a collection with all users
                        users = User.all

                        # return the first user
                        user = User.first

                        # return the first user named David
                        david = User.find_by(name: 'David')

                        # find all users named David who are Code Artists and sort by created_at in reverse chronological order
                        users = User.where(name: 'David', occupation: 'Code Artist').order('created_at DESC')


            Update
                        user = User.find_by(name: 'David')
                        user.name = 'Dave'
                        user.save

                        user = User.find_by(name: 'David')
                        user.update(name: 'Dave')

                        User.update_all
                        "max_login_attempts = 3, must_change_password = 'true'"

            Delete
                        user = User.find_by(name: 'David')
                        user.destroy

            Validation
                        http://guides.rubyonrails.org/active_record_validations.html
              Ex:
                        class
                         
                        User < ActiveRecord::Base
                         
                             validates :name, presence: true
                        end
             
                        User.create 
                        # => false
                        User.create!
                        # => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank

            Callbacks
              http://guides.rubyonrails.org/active_record_callbacks.html
               Attach code to certain events in the life-cycle of your models.  Allows to include behavior to the model transparently executing code when some event happens.  Ex, when you create, update or delete a object.

            Migration
            http://guides.rubyonrails.org/migrations.html
               Uses a DSL for managing a database schema.  Migration files are executed against any DB that Active Record supports using Rake
                        Ex:
                        class CreatePublications < ActiveRecord::Migration
                         
                          def change
                           
                                   create_table :publications do |t|
                                                t.string :title
                                                t.text                :description
                                                t.references      :publication_type
                                                t.integer            :publisher_id
                                                t.string :publisher_type
                                                t.boolean          :single_issue
                              
                                               t.timestamps
                                    end
                                    add_index :publications, :publication_type_id
                          end
                        end
            Comands of rake
                        rake db:drop
                        rake db:resed
                        rake db:migrate

                        rake db:populate
                         rake test:prepare

            

Nenhum comentário:

Postar um comentário