SlideShare uma empresa Scribd logo
1 de 67
The 8th Round of ROR Lab.



Active Record
Associations - 2

       March 3rd, 2012

       Hyoseong Choi
         ROR Lab.
Short Review


               ROR Lab.
For what?
   Primary & Foreign Keys
customer               order
   id                       id




                                 ROR Lab.
For what?
     Primary & Foreign Keys
customer                 order
    id                        id
                      customer_id

parent obj.            child obj.


                                    ROR Lab.
For what?
     Primary & Foreign Keys
customer                        order
    id                             id
              Active Record   customer_id
               Assocation


parent obj.                    child obj.


                                            ROR Lab.
For what?




            ROR Lab.
For what?


To add an order




                     ROR Lab.
For what?


To add an order




                     ROR Lab.
For what?


To add an order

To delete a customer




                       ROR Lab.
For what?


To add an order

To delete a customer




                       ROR Lab.
Associations
             Parent Class        Child Class
               has_one
1 :1                             belongs_to
           has_one, :through
1 :n          has_many           belongs_to
                has_many
       A
           has_many B, :through
                                 belongs_to
n :m            has_many
       B
           has_many A, :through
             has_and_belongs_to_many
                                     ROR Lab.
Association Options
belongs_to options   has_one options   has_many options   HABTM options
• :autosave          • :as             • :as              • :association_foreign_key
• :class_name        • :autosave       • :autosave        • :autosave
• :conditions        • :class_name     • :class_name      • :class_name
• :counter_cache     • :conditions     • :conditions      • :conditions
• :dependent         • :dependent      • :counter_sql     • :counter_sql
• :foreign_key       • :foreign_key    • :dependent       • :delete_sql
• :include           • :include        • :extend          • :extend
• :polymorphic       • :order          • :finder_sql      • :finder_sql
• :readonly          • :primary_key    • :foreign_key     • :foreign_key
• :select            • :readonly       • :group           • :group
• :touch             • :select         • :include         • :include
• :validate          • :source         • :limit           • :insert_sql
                     • :source_type    • :offset          • :join_table
                     • :through        • :order           • :limit
                     • :validate       • :primary_key     • :offset
                                       • :readonly        • :order
                                       • :select          • :readonly
                                       • :source          • :select
                                       • :source_type     • :uniq
                                       • :through         • :validate
                                       • :uniq
                                       • :validate


                                                                   ROR Lab.
Polymorphic
  Imageable       Picture

       id     imageable_id



  Imageable       Picture

       id     imageable_id



                             ROR Lab.
Polymorphic
  Imageable       Picture
  Employee

      id id   imageable_id



  Imageable       Picture
  Product

      id id   imageable_id



                             ROR Lab.
:counter_cache
• But, you should add “orders_count”
  column to Customer model
• You can override the default column name.
• ReadOnly !!!



                                       ROR Lab.
:counter_cache
• But, you should add “orders_count”
  column to Customer model
• You can override the default column name.
• ReadOnly !!!



                                       ROR Lab.
:touch




         ROR Lab.
:touch




         ROR Lab.
:touch



Or using a custom attribute




                              ROR Lab.
:touch



Or using a custom attribute




                              ROR Lab.
ActiveRecord
Association - 2


              ROR Lab.
Association Options
belongs_to options   has_one options   has_many options   HABTM options
• :autosave          • :autosave       • :autosave        • :autosave
• :class_name        • :class_name     • :class_name      • :class_name
• :conditions        • :conditions     • :conditions      • :conditions
• :foreign_key       • :foreign_key    • :foreign_key     • :foreign_key
• :include           • :include        • :include         • :include
• :readonly          • :readonly       • :readonly        • :readonly
• :select            • :select         • :select          • :select
• :validate          • :validate       • :validate        • :validate
• :dependent         • :as             • :as              • :order
• :counter_cache     • :order          • :order           • :counter_sql
• :polymorphic       • :primary_key    • :primary_key     • :extend
• :touch             • :source         • :source          • :finder_sql
                     • :source_type    • :source_type     • :group
                     • :through        • :through         • :limit
                     • :dependent      • :counter_sql     • :offset
                                       • :extend          • :uniq
                                       • :finder_sql      • :association_foreign_key
                                       • :group           • :delete_sql
                                       • :limit           • :insert_sql
                                       • :offset          • :join_table
                                       • :uniq
                                       • :dependent


                                                                   ROR Lab.
Association Options
belongs_to options   has_one options   has_many options   HABTM options
• :autosave          • :autosave       • :autosave        • :autosave
• :class_name        • :class_name     • :class_name      • :class_name
• :conditions        • :conditions     • :conditions      • :conditions
• :foreign_key       • :foreign_key    • :foreign_key     • :foreign_key
• :include           • :include        • :include         • :include
• :readonly          • :readonly       • :readonly        • :readonly
• :select            • :select         • :select          • :select
• :validate          • :validate       • :validate        • :validate
• :dependent         • :as             • :as              • :order
• :counter_cache     • :order          • :order           • :counter_sql
• :polymorphic       • :primary_key    • :primary_key     • :extend
• :touch             • :source         • :source          • :finder_sql
                     • :source_type    • :source_type     • :group
                     • :through        • :through         • :limit
                     • :dependent      • :counter_sql     • :offset
                                       • :extend          • :uniq
                                       • :finder_sql      • :association_foreign_key
                                       • :group           • :delete_sql
                                       • :limit           • :insert_sql
                                       • :offset          • :join_table
                                       • :uniq
                                       • :dependent


                                                                   ROR Lab.
Association Options
belongs_to options   has_one options   has_many options   HABTM options
• :autosave          • :autosave       • :autosave        • :autosave
• :class_name        • :class_name     • :class_name      • :class_name
• :conditions        • :conditions     • :conditions      • :conditions
• :foreign_key       • :foreign_key    • :foreign_key     • :foreign_key
• :include           • :include        • :include         • :include
• :readonly          • :readonly       • :readonly        • :readonly
• :select            • :select         • :select          • :select
• :validate          • :validate       • :validate        • :validate
• :dependent         • :as             • :as              • :order
• :counter_cache     • :order          • :order           • :counter_sql
• :polymorphic       • :primary_key    • :primary_key     • :extend
• :touch             • :source         • :source          • :finder_sql
                     • :source_type    • :source_type     • :group
                     • :through        • :through         • :limit
                     • :dependent      • :counter_sql     • :offset
                                       • :extend          • :uniq
                                       • :finder_sql      • :association_foreign_key
                                       • :group           • :delete_sql
                                       • :limit           • :insert_sql
                                       • :offset          • :join_table
                                       • :uniq
                                       • :dependent


                                                                   ROR Lab.
Association Options
belongs_to options   has_one options   has_many options   HABTM options
• :autosave          • :autosave       • :autosave        • :autosave
• :class_name        • :class_name     • :class_name      • :class_name
• :conditions        • :conditions     • :conditions      • :conditions
• :foreign_key       • :foreign_key    • :foreign_key     • :foreign_key
• :include           • :include        • :include         • :include
• :readonly          • :readonly       • :readonly        • :readonly
• :select            • :select         • :select          • :select
• :validate          • :validate       • :validate        • :validate
• :dependent         • :as             • :as              • :order
• :counter_cache     • :order          • :order           • :counter_sql
• :polymorphic       • :primary_key    • :primary_key     • :extend
• :touch             • :source         • :source          • :finder_sql
                     • :source_type    • :source_type     • :group
                     • :through        • :through         • :limit
                     • :dependent      • :counter_sql     • :offset
                                       • :extend          • :uniq
                                       • :finder_sql      • :association_foreign_key
                                       • :group           • :delete_sql
                                       • :limit           • :insert_sql
                                       • :offset          • :join_table
                                       • :uniq
                                       • :dependent


                                                                   ROR Lab.
Association Options
belongs_to options   has_one options   has_many options   HABTM options
• :autosave          • :autosave       • :autosave        • :autosave
• :class_name        • :class_name     • :class_name      • :class_name
• :conditions        • :conditions     • :conditions      • :conditions
• :foreign_key       • :foreign_key    • :foreign_key     • :foreign_key
• :include           • :include        • :include         • :include
• :readonly          • :readonly       • :readonly        • :readonly
• :select            • :select         • :select          • :select
• :validate          • :validate       • :validate        • :validate
• :dependent         • :as             • :as              • :order
• :counter_cache     • :order          • :order           • :counter_sql
• :polymorphic       • :primary_key    • :primary_key     • :extend
• :touch             • :source         • :source          • :finder_sql
                     • :source_type    • :source_type     • :group
                     • :through        • :through         • :limit
                     • :dependent      • :counter_sql     • :offset
                                       • :extend          • :uniq
                                       • :finder_sql      • :association_foreign_key
                                       • :group           • :delete_sql
                                       • :limit           • :insert_sql
                                       • :offset          • :join_table
                                       • :uniq
                                       • :dependent


                                                                   ROR Lab.
Association Options
belongs_to options   has_one options   has_many options   HABTM options
• :autosave          • :autosave       • :autosave        • :autosave
• :class_name        • :class_name     • :class_name      • :class_name
• :conditions        • :conditions     • :conditions      • :conditions
• :foreign_key       • :foreign_key    • :foreign_key     • :foreign_key
• :include           • :include        • :include         • :include
• :readonly          • :readonly       • :readonly        • :readonly
• :select            • :select         • :select          • :select
• :validate          • :validate       • :validate        • :validate
• :dependent         • :as             • :as              • :order
• :counter_cache     • :order          • :order           • :counter_sql
• :polymorphic       • :primary_key    • :primary_key     • :extend
• :touch             • :source         • :source          • :finder_sql
                     • :source_type    • :source_type     • :group
                     • :through        • :through         • :limit
                     • :dependent      • :counter_sql     • :offset
                                       • :extend          • :uniq
                                       • :finder_sql      • :association_foreign_key
                                       • :group           • :delete_sql
                                       • :limit           • :insert_sql
                                       • :offset          • :join_table
                                       • :uniq
                                       • :dependent


                                                                   ROR Lab.
Association Options
belongs_to options   has_one options   has_many options   HABTM options
• :autosave          • :autosave       • :autosave        • :autosave
• :class_name        • :class_name     • :class_name      • :class_name
• :conditions        • :conditions     • :conditions      • :conditions
• :foreign_key       • :foreign_key    • :foreign_key     • :foreign_key
• :include           • :include        • :include         • :include
• :readonly          • :readonly       • :readonly        • :readonly
• :select            • :select         • :select          • :select
• :validate          • :validate       • :validate        • :validate
• :dependent         • :as             • :as              • :order
• :counter_cache     • :order          • :order           • :counter_sql
• :polymorphic       • :primary_key    • :primary_key     • :extend
• :touch             • :source         • :source          • :finder_sql
                     • :source_type    • :source_type     • :group
                     • :through        • :through         • :limit
                     • :dependent      • :counter_sql     • :offset
                                       • :extend          • :uniq
                                       • :finder_sql      • :association_foreign_key
                                       • :group           • :delete_sql
                                       • :limit           • :insert_sql
                                       • :offset          • :join_table
                                       • :uniq
                                       • :dependent


                                                                   ROR Lab.
Association Options
belongs_to options   has_one options   has_many options   HABTM options
• :autosave          • :autosave       • :autosave        • :autosave
• :class_name        • :class_name     • :class_name      • :class_name
• :conditions        • :conditions     • :conditions      • :conditions
• :foreign_key       • :foreign_key    • :foreign_key     • :foreign_key
• :include           • :include        • :include         • :include
• :readonly          • :readonly       • :readonly        • :readonly
• :select            • :select         • :select          • :select
• :validate          • :validate       • :validate        • :validate
• :dependent         • :as             • :as              • :order
• :counter_cache     • :order          • :order           • :counter_sql
• :polymorphic       • :primary_key    • :primary_key     • :extend
• :touch             • :source         • :source          • :finder_sql
                     • :source_type    • :source_type     • :group
                     • :through        • :through         • :limit
                     • :dependent      • :counter_sql     • :offset
                                       • :extend          • :uniq
                                       • :finder_sql      • :association_foreign_key
                                       • :group           • :delete_sql
                                       • :limit           • :insert_sql
                                       • :offset          • :join_table
                                       • :uniq
                                       • :dependent


                                                                   ROR Lab.
Common Options
• :autosave
• :class_name
• :conditions
• :foreign_key
• :include
• :readonly
• :select
• :validate
                 ROR Lab.
- common options -

                     :autosave
       • No declaration (default)
           : new children are saved when their parent
           is saved
       • :autosave => true
           : all children is saved, no matter whether
           they are new records
       • :autosave => false
           : any children is not saved
                                                  ROR Lab.
- common options -

                                    :autosave
          class Post
           has_one :author, :autosave => true
          end
                                                                               has_one
          post = Post.find(1)
          post.title   # => "The current global position of migrating ducks"
          post.author.name # => "alloy"

          post.title = "On the migration of ducks"
          post.author.name = "Eloy Duran"

          post.save
          post.reload
          post.title   # => "On the migration of ducks"
          post.author.name # => "Eloy Duran"

          post.author.mark_for_destruction
          post.author.marked_for_destruction? # => true

          id = post.author.id
          Author.find_by_id(id).nil? # => false

          post.save
          post.reload.author # => nil

          Author.find_by_id(id).nil? # => true




               http://api.rubyonrails.org/classes/ActiveRecord/AutosaveAssociation.html

                                                                                      ROR Lab.
- common options -                                 :autosave

                                                                           has_many
          class Post
            has_many :comments # :autosave option is no declared
          end

          post = Post.new(:title => 'ruby rocks')
          post.comments.build(:body => 'hello world')
          post.save # => saves both post and comment

          post = Post.create(:title => 'ruby rocks')
          post.comments.build(:body => 'hello world')
          post.save # => saves both post and comment

          post = Post.create(:title => 'ruby rocks')
          post.comments.create(:body => 'hello world')
          post.save # => saves both post and comment

          class Post
            has_many :comments, :autosave => true
          end

          post = Post.create(:title => 'ruby rocks')
          post.comments.create(:body => 'hello world')
          post.comments[0].body = 'hi everyone'
          post.save # => saves both post and comment, with 'hi everyone' as body

          post.comments.last.mark_for_destruction
          post.comments.last.marked_for_destruction? # => true
          post.comments.length # => 2

          id = post.comments.last.id
          Comment.find_by_id(id).nil? # => false

          post.save
          post.reload.comments.length # => 1

          Comment.find_by_id(id).nil? # => true




                                                                                   ROR Lab.
- common options -

                  :class_name

          class Order < ActiveRecord::Base
            belongs_to :customer, :class_name => "Patron"
          end




                                                            ROR Lab.
- common options -

                     :conditions

          class Order < ActiveRecord::Base
            belongs_to :customer, :conditions => "active = 1"
          end




                                                                ROR Lab.
- common options -

                 :foreign_key

          class Order < ActiveRecord::Base
            belongs_to :customer, :class_name => "Patron",
              :foreign_key => "patron_id"
          end




                                                             ROR Lab.
- common options -

                          :include
          class LineItem < ActiveRecord::Base
            belongs_to :order, :include => :customer
          end
           
          class Order < ActiveRecord::Base
            belongs_to :customer
            has_many :line_items
          end
           
          class Customer < ActiveRecord::Base
            has_many :orders
          end



                                                       ROR Lab.
- common options -

                      :readonly

          class Customer < ActiveRecord::Base
            has_many :orders, :readonly => true
          end




                                                  ROR Lab.
- common options -

                            :select
          class Order < ActiveRecord::Base
            belongs_to :customer,
                  :select => "name, profile, group_id"
          end




                                                        ROR Lab.
- common options -

                        :validate

          class Order < ActiveRecord::Base
            belongs_to :customer, :validate => true
          end




                                                      ROR Lab.
Common
        has_ Options
              has_one / has_many

• :as
• :order* (also, included in HABTM)
• :primary_key
• :source
• :source_type
• :through


                                      ROR Lab.
- common has_ options -

                                  :as
          class Picture < ActiveRecord::Base
            belongs_to :imageable, :polymorphic => true
          end
           
          class Employee < ActiveRecord::Base
            has_many :pictures, :as => :imageable
          end
           
          class Product < ActiveRecord::Base
            has_many :pictures, :as => :imageable
          end




                                                          ROR Lab.
- common has_ options -

                             :order

          class Post < ActiveRecord::Base
            has_many :comments, :order => ”updated_at”
          end




          •also, in HABTM



                                                         ROR Lab.
- common has_ options -

               :primary_key
          class Order < ActiveRecord::Base                   default
            belongs_to :customer,
                  :primary_key => "id",
                  :foreign_key => "customer_id"




          class Order < ActiveRecord::Base
            belongs_to :customer, :class_name => "Patron",
                  :primary_key => "civil_no",
                  :foreign_key => "patron_id"



                                                                 ROR Lab.
- common has_ options -

       :source & :source_type
           class Tag < ActiveRecord::Base
             has_many :taggings, :dependent => :destroy
             has_many :books, :through => :tagings, :source => :taggable, :source_type => "Book"
             has_many :movies, :through => :tagings, :source => :taggable, :source_type => "Movie"
           end

           class Tagging < ActiveRecord::Base
             belongs_to :taggable, :polymorphic => true
             belongs_to :tag
           end

           class Book < ActiveRecord::Base
             has_many :taggings, :as => :taggable
             has_many :tags, :through => :taggings
           end

           class Movie < ActiveRecord::Base
             has_many :taggings, :as => :taggable
             has_many :tags, :through => :taggings
           end




       •   http://www.brentmc79.com/posts/polymorphic-many-to-many-associations-in-rails


                                                                                             ROR Lab.
- common has_ options -

                        :through
          class Supplier < ActiveRecord::Base
            has_one :account
            has_one :account_history, :through => :account
          end
           
          class Account < ActiveRecord::Base
            belongs_to :supplier
            has_one :account_history
          end
           
          class AccountHistory < ActiveRecord::Base
            belongs_to :account
          end



                                                             ROR Lab.
Common
     _many Options
                 has_many / HABTM

• :counter_sql
• :extend
• :finder_sql
• :group
• :limit
• :offset
• :uniq
                                    ROR Lab.
- common _many options -

                     :finder_sql
       class Person < ActiveRecord::Base
        has_many :subscribers,
                :class_name => "Person",
                :finder_sql => Proc.new {
          %Q{
            SELECT DISTINCT *
            FROM people p, post_subscriptions ps
            WHERE ps.post_id = #{id} AND ps.person_id = p.id
            ORDER BY p.first_name
          }
        }




                                                               ROR Lab.
- common _many options -

                  :counter_sql
       class Person < ActiveRecord::Base
        has_many :subscribers,
                :class_name => "Person",
                :counter_sql => Proc.new {
          %Q{
            SELECT DISTINCT *
            FROM people p, post_subscriptions ps
            WHERE ps.post_id = #{id} AND ps.person_id = p.id
            ORDER BY p.first_name
          }
        }




                                                               ROR Lab.
- common _many options -

                           :extend
      association proxy(or interface)

       class Customer < ActiveRecord::Base
         has_many :orders do
           def find_by_order_prefix(order_number)
             find_by_region_id(order_number[0..2])
           end
         end




                                                    ROR Lab.
- common _many options -

                          :extend
       module FindRecentExtension
         def find_recent
           where("created_at > ?", 5.days.ago)
         end
       end
        
       class Customer < ActiveRecord::Base
         has_many :orders, :extend => FindRecentExtension
       end
        
       class Supplier < ActiveRecord::Base
         has_many :deliveries, :extend => FindRecentExtension




                                                                ROR Lab.
- common _many options -

                             :extend
       class Customer < ActiveRecord::Base
         has_many :orders,
           :extend => [FindRecentExtension, FindActiveExtension]
       end




                                                                   ROR Lab.
- common _many options -
                           *
            3 AP accessors

       • proxy_association.owner
       • proxy_association.reflection
       • proxy_association.target

       AP* : Association Proxy

                                       ROR Lab.
- common _many options -

                            :group
       class Customer < ActiveRecord::Base
         has_many :line_items,
              :through => :orders,
              :group => "orders.id"
       end




                                             ROR Lab.
- common _many options -

              :limit / :offset
       class Customer < ActiveRecord::Base
         has_many :recent_orders,
              :class_name => "Order",
              :order => "order_date DESC",
              :limit => 100
              :offset => 300




                                             ROR Lab.
- common _many options -

                                 :uniq
       class Person < ActiveRecord::Base
         has_many :readings
         has_many :posts, :through => :readings
       end
        
       person = Person.create(:name => 'john')
       post   = Post.create(:name => 'a1')
       person.posts << post
       person.posts << post
       person.posts.inspect # => [#<Post id: 5, name: "a1">, #<Post id: 5,
       name: "a1">]
       Reading.all.inspect  # => [#<Reading id: 12, person_id: 5, post_id: 5>,
       #<Reading id: 13, person_id: 5, post_id: 5>]




                                                                      ROR Lab.
- common _many options -

                                 :uniq
       class Person
         has_many :readings
         has_many :posts, :through => :readings, :uniq => true
       end
        
       person = Person.create(:name => 'honda')
       post   = Post.create(:name => 'a1')
       person.posts << post
       person.posts << post
       person.posts.inspect # => [#<Post id: 7, name: "a1">]
       Reading.all.inspect  # => [#<Reading id: 16, person_id: 7, post_id: 7>,
       #<Reading id: 17, person_id: 7, post_id: 7>]




                                                                      ROR Lab.
Common
  one-way Options
         belongs_to / has_one / has_many
• :dependent
 class Comment < ActiveRecord::Base
   belongs_to :post, :dependent => :destroy
 end



 class Post < ActiveRecord::Base
   has_many :comments, :dependent => :destroy
 end


                                                ROR Lab.
Special Options
• belongs_to
  • :counter_cache
  • :polymorphic
  • :touch
• HABTM
  • :association_foreign_key
  • :delete_sql
  • :insert_sql
  • :join_table

                               ROR Lab.
- special options for HABTM -

      :association_foreign_key

        class User < ActiveRecord::Base
          has_and_belongs_to_many :friends,
            :class_name => "User",
            :foreign_key => "this_user_id",
            :association_foreign_key => "other_user_id"




                         many-to-many self join



                                                          ROR Lab.
- special options for HABTM -

                     :delete_sql
        class Developer < ActiveRecord::Base
          has_and_belongs_to_many :active_projects,
            :join_table => 'developers_projects',
            :delete_sql =>
               "DELETE FROM developers_projects WHERE active=1
                AND developer_id = #{id}
                AND project_id = #{record.id}"
        end




                                                                 ROR Lab.
- special options for HABTM -

                      :insert_sql
        class Developer < ActiveRecord::Base
          has_and_belongs_to_many :active_projects,
            :join_table => 'developers_projects',
            :insert_sql =>
               "INSERT INTO developers_projects
                VALUES(#{id},#{record.id})"
        end




                                                      ROR Lab.
- special options for HABTM -

                      :join_table
        class Category < ActiveRecord::Base
          has_and_belongs_to_many :products,
                         :join_table => “cats_prods”
        end
         
        class Product < ActiveRecord::Base
          has_and_belongs_to_many :categories,
                         :join_table => “cats_prods”




         default join table => “categories_products”


                                                       ROR Lab.
Association Callbacks

• in the lifecycle of a collection
 • before_add
 • after_add
 • before_remove
 • after_remove
                                     ROR Lab.
Association Callbacks
class Customer < ActiveRecord::Base
  has_many :orders, :before_add => :check_credit_limit
 
  def check_credit_limit(order)
    ...
  end
end

class Customer < ActiveRecord::Base
  has_many :orders,
    :before_add =>
        [:check_credit_limit, :calculate_shipping_charges]
 
  def check_credit_limit(order)
    ...
  end
 
  def calculate_shipping_charges(order)
    ...
  end


                                                             ROR Lab.
Summary


• http://jonathanhui.com/ruby-rails-3-model-
  association




                                       ROR Lab.
감사합니다.

Mais conteúdo relacionado

Semelhante a ActiveRecord Associations (2), Season 1

Stardog Linked Data Catalog
Stardog Linked Data CatalogStardog Linked Data Catalog
Stardog Linked Data Catalogkendallclark
 
Refactoring RIA Unleashed 2011
Refactoring RIA Unleashed 2011Refactoring RIA Unleashed 2011
Refactoring RIA Unleashed 2011Jesse Warden
 
My Little Webap - DevOpsSec is Magic
My Little Webap - DevOpsSec is MagicMy Little Webap - DevOpsSec is Magic
My Little Webap - DevOpsSec is MagicApollo Clark
 
Authentication in-rails
Authentication in-railsAuthentication in-rails
Authentication in-railsMihir Vaidya
 
Developer testing 201: When to Mock and When to Integrate
Developer testing 201: When to Mock and When to IntegrateDeveloper testing 201: When to Mock and When to Integrate
Developer testing 201: When to Mock and When to IntegrateLB Denker
 
ActiveRecord Validations, Season 2
ActiveRecord Validations, Season 2ActiveRecord Validations, Season 2
ActiveRecord Validations, Season 2RORLAB
 
The business case for contributing code
The business case for contributing codeThe business case for contributing code
The business case for contributing codeZivtech, LLC
 
GDD Moscow - Open Social
GDD Moscow - Open SocialGDD Moscow - Open Social
GDD Moscow - Open SocialChris Chabot
 
ActiveRecord Callbacks & Observers, Season 2
ActiveRecord Callbacks & Observers, Season 2ActiveRecord Callbacks & Observers, Season 2
ActiveRecord Callbacks & Observers, Season 2RORLAB
 
Natural Language Processing - Principles and Practice - Gracie Diaz
Natural Language Processing - Principles and Practice - Gracie DiazNatural Language Processing - Principles and Practice - Gracie Diaz
Natural Language Processing - Principles and Practice - Gracie DiazCatalina Arango
 
Rest api to integrate with your site
Rest api to integrate with your siteRest api to integrate with your site
Rest api to integrate with your siteLuis Goldster
 
Rest api to integrate with your site
Rest api to integrate with your siteRest api to integrate with your site
Rest api to integrate with your siteHoang Nguyen
 
Rest api to integrate with your site
Rest api to integrate with your siteRest api to integrate with your site
Rest api to integrate with your siteFraboni Ec
 
Rest api to integrate with your site
Rest api to integrate with your siteRest api to integrate with your site
Rest api to integrate with your siteJames Wong
 
Rest api to integrate with your site
Rest api to integrate with your siteRest api to integrate with your site
Rest api to integrate with your siteTony Nguyen
 
Rest api to integrate with your site
Rest api to integrate with your siteRest api to integrate with your site
Rest api to integrate with your siteYoung Alista
 
Rest api to integrate with your site
Rest api to integrate with your siteRest api to integrate with your site
Rest api to integrate with your siteHarry Potter
 
Inside Of Mbga Open Platform
Inside Of Mbga Open PlatformInside Of Mbga Open Platform
Inside Of Mbga Open PlatformHideo Kimura
 

Semelhante a ActiveRecord Associations (2), Season 1 (20)

Stardog Linked Data Catalog
Stardog Linked Data CatalogStardog Linked Data Catalog
Stardog Linked Data Catalog
 
Stardog Linked Data Catalog
Stardog Linked Data CatalogStardog Linked Data Catalog
Stardog Linked Data Catalog
 
Refactoring RIA Unleashed 2011
Refactoring RIA Unleashed 2011Refactoring RIA Unleashed 2011
Refactoring RIA Unleashed 2011
 
My Little Webap - DevOpsSec is Magic
My Little Webap - DevOpsSec is MagicMy Little Webap - DevOpsSec is Magic
My Little Webap - DevOpsSec is Magic
 
Authentication in-rails
Authentication in-railsAuthentication in-rails
Authentication in-rails
 
Developer testing 201: When to Mock and When to Integrate
Developer testing 201: When to Mock and When to IntegrateDeveloper testing 201: When to Mock and When to Integrate
Developer testing 201: When to Mock and When to Integrate
 
ActiveRecord Validations, Season 2
ActiveRecord Validations, Season 2ActiveRecord Validations, Season 2
ActiveRecord Validations, Season 2
 
The business case for contributing code
The business case for contributing codeThe business case for contributing code
The business case for contributing code
 
GDD Moscow - Open Social
GDD Moscow - Open SocialGDD Moscow - Open Social
GDD Moscow - Open Social
 
Ar search skills
Ar search skillsAr search skills
Ar search skills
 
ActiveRecord Callbacks & Observers, Season 2
ActiveRecord Callbacks & Observers, Season 2ActiveRecord Callbacks & Observers, Season 2
ActiveRecord Callbacks & Observers, Season 2
 
Natural Language Processing - Principles and Practice - Gracie Diaz
Natural Language Processing - Principles and Practice - Gracie DiazNatural Language Processing - Principles and Practice - Gracie Diaz
Natural Language Processing - Principles and Practice - Gracie Diaz
 
Rest api to integrate with your site
Rest api to integrate with your siteRest api to integrate with your site
Rest api to integrate with your site
 
Rest api to integrate with your site
Rest api to integrate with your siteRest api to integrate with your site
Rest api to integrate with your site
 
Rest api to integrate with your site
Rest api to integrate with your siteRest api to integrate with your site
Rest api to integrate with your site
 
Rest api to integrate with your site
Rest api to integrate with your siteRest api to integrate with your site
Rest api to integrate with your site
 
Rest api to integrate with your site
Rest api to integrate with your siteRest api to integrate with your site
Rest api to integrate with your site
 
Rest api to integrate with your site
Rest api to integrate with your siteRest api to integrate with your site
Rest api to integrate with your site
 
Rest api to integrate with your site
Rest api to integrate with your siteRest api to integrate with your site
Rest api to integrate with your site
 
Inside Of Mbga Open Platform
Inside Of Mbga Open PlatformInside Of Mbga Open Platform
Inside Of Mbga Open Platform
 

Mais de RORLAB

Getting Started with Rails (4)
Getting Started with Rails (4) Getting Started with Rails (4)
Getting Started with Rails (4) RORLAB
 
Getting Started with Rails (3)
Getting Started with Rails (3) Getting Started with Rails (3)
Getting Started with Rails (3) RORLAB
 
Getting Started with Rails (2)
Getting Started with Rails (2)Getting Started with Rails (2)
Getting Started with Rails (2)RORLAB
 
Getting Started with Rails (1)
Getting Started with Rails (1)Getting Started with Rails (1)
Getting Started with Rails (1)RORLAB
 
Self join in active record association
Self join in active record associationSelf join in active record association
Self join in active record associationRORLAB
 
Asset Pipeline in Ruby on Rails
Asset Pipeline in Ruby on RailsAsset Pipeline in Ruby on Rails
Asset Pipeline in Ruby on RailsRORLAB
 
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개RORLAB
 
Active Support Core Extension (3)
Active Support Core Extension (3)Active Support Core Extension (3)
Active Support Core Extension (3)RORLAB
 
Active Support Core Extension (2)
Active Support Core Extension (2)Active Support Core Extension (2)
Active Support Core Extension (2)RORLAB
 
Active Support Core Extensions (1)
Active Support Core Extensions (1)Active Support Core Extensions (1)
Active Support Core Extensions (1)RORLAB
 
Action Controller Overview, Season 2
Action Controller Overview, Season 2Action Controller Overview, Season 2
Action Controller Overview, Season 2RORLAB
 
Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2RORLAB
 
Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2RORLAB
 
Layouts and Rendering in Rails, Season 2
Layouts and Rendering in Rails, Season 2Layouts and Rendering in Rails, Season 2
Layouts and Rendering in Rails, Season 2RORLAB
 
ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2RORLAB
 
Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2RORLAB
 
Rails Database Migration, Season 2
Rails Database Migration, Season 2Rails Database Migration, Season 2
Rails Database Migration, Season 2RORLAB
 
Getting started with Rails (4), Season 2
Getting started with Rails (4), Season 2Getting started with Rails (4), Season 2
Getting started with Rails (4), Season 2RORLAB
 
Getting started with Rails (3), Season 2
Getting started with Rails (3), Season 2Getting started with Rails (3), Season 2
Getting started with Rails (3), Season 2RORLAB
 
Getting started with Rails (2), Season 2
Getting started with Rails (2), Season 2Getting started with Rails (2), Season 2
Getting started with Rails (2), Season 2RORLAB
 

Mais de RORLAB (20)

Getting Started with Rails (4)
Getting Started with Rails (4) Getting Started with Rails (4)
Getting Started with Rails (4)
 
Getting Started with Rails (3)
Getting Started with Rails (3) Getting Started with Rails (3)
Getting Started with Rails (3)
 
Getting Started with Rails (2)
Getting Started with Rails (2)Getting Started with Rails (2)
Getting Started with Rails (2)
 
Getting Started with Rails (1)
Getting Started with Rails (1)Getting Started with Rails (1)
Getting Started with Rails (1)
 
Self join in active record association
Self join in active record associationSelf join in active record association
Self join in active record association
 
Asset Pipeline in Ruby on Rails
Asset Pipeline in Ruby on RailsAsset Pipeline in Ruby on Rails
Asset Pipeline in Ruby on Rails
 
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
 
Active Support Core Extension (3)
Active Support Core Extension (3)Active Support Core Extension (3)
Active Support Core Extension (3)
 
Active Support Core Extension (2)
Active Support Core Extension (2)Active Support Core Extension (2)
Active Support Core Extension (2)
 
Active Support Core Extensions (1)
Active Support Core Extensions (1)Active Support Core Extensions (1)
Active Support Core Extensions (1)
 
Action Controller Overview, Season 2
Action Controller Overview, Season 2Action Controller Overview, Season 2
Action Controller Overview, Season 2
 
Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2
 
Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2
 
Layouts and Rendering in Rails, Season 2
Layouts and Rendering in Rails, Season 2Layouts and Rendering in Rails, Season 2
Layouts and Rendering in Rails, Season 2
 
ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2
 
Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2
 
Rails Database Migration, Season 2
Rails Database Migration, Season 2Rails Database Migration, Season 2
Rails Database Migration, Season 2
 
Getting started with Rails (4), Season 2
Getting started with Rails (4), Season 2Getting started with Rails (4), Season 2
Getting started with Rails (4), Season 2
 
Getting started with Rails (3), Season 2
Getting started with Rails (3), Season 2Getting started with Rails (3), Season 2
Getting started with Rails (3), Season 2
 
Getting started with Rails (2), Season 2
Getting started with Rails (2), Season 2Getting started with Rails (2), Season 2
Getting started with Rails (2), Season 2
 

Último

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 

Último (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 

ActiveRecord Associations (2), Season 1

  • 1. The 8th Round of ROR Lab. Active Record Associations - 2 March 3rd, 2012 Hyoseong Choi ROR Lab.
  • 2. Short Review ROR Lab.
  • 3. For what? Primary & Foreign Keys customer order id id ROR Lab.
  • 4. For what? Primary & Foreign Keys customer order id id customer_id parent obj. child obj. ROR Lab.
  • 5. For what? Primary & Foreign Keys customer order id id Active Record customer_id Assocation parent obj. child obj. ROR Lab.
  • 6. For what? ROR Lab.
  • 7. For what? To add an order ROR Lab.
  • 8. For what? To add an order ROR Lab.
  • 9. For what? To add an order To delete a customer ROR Lab.
  • 10. For what? To add an order To delete a customer ROR Lab.
  • 11. Associations Parent Class Child Class has_one 1 :1 belongs_to has_one, :through 1 :n has_many belongs_to has_many A has_many B, :through belongs_to n :m has_many B has_many A, :through has_and_belongs_to_many ROR Lab.
  • 12. Association Options belongs_to options has_one options has_many options HABTM options • :autosave • :as • :as • :association_foreign_key • :class_name • :autosave • :autosave • :autosave • :conditions • :class_name • :class_name • :class_name • :counter_cache • :conditions • :conditions • :conditions • :dependent • :dependent • :counter_sql • :counter_sql • :foreign_key • :foreign_key • :dependent • :delete_sql • :include • :include • :extend • :extend • :polymorphic • :order • :finder_sql • :finder_sql • :readonly • :primary_key • :foreign_key • :foreign_key • :select • :readonly • :group • :group • :touch • :select • :include • :include • :validate • :source • :limit • :insert_sql • :source_type • :offset • :join_table • :through • :order • :limit • :validate • :primary_key • :offset • :readonly • :order • :select • :readonly • :source • :select • :source_type • :uniq • :through • :validate • :uniq • :validate ROR Lab.
  • 13. Polymorphic Imageable Picture id imageable_id Imageable Picture id imageable_id ROR Lab.
  • 14. Polymorphic Imageable Picture Employee id id imageable_id Imageable Picture Product id id imageable_id ROR Lab.
  • 15. :counter_cache • But, you should add “orders_count” column to Customer model • You can override the default column name. • ReadOnly !!! ROR Lab.
  • 16. :counter_cache • But, you should add “orders_count” column to Customer model • You can override the default column name. • ReadOnly !!! ROR Lab.
  • 17. :touch ROR Lab.
  • 18. :touch ROR Lab.
  • 19. :touch Or using a custom attribute ROR Lab.
  • 20. :touch Or using a custom attribute ROR Lab.
  • 22. Association Options belongs_to options has_one options has_many options HABTM options • :autosave • :autosave • :autosave • :autosave • :class_name • :class_name • :class_name • :class_name • :conditions • :conditions • :conditions • :conditions • :foreign_key • :foreign_key • :foreign_key • :foreign_key • :include • :include • :include • :include • :readonly • :readonly • :readonly • :readonly • :select • :select • :select • :select • :validate • :validate • :validate • :validate • :dependent • :as • :as • :order • :counter_cache • :order • :order • :counter_sql • :polymorphic • :primary_key • :primary_key • :extend • :touch • :source • :source • :finder_sql • :source_type • :source_type • :group • :through • :through • :limit • :dependent • :counter_sql • :offset • :extend • :uniq • :finder_sql • :association_foreign_key • :group • :delete_sql • :limit • :insert_sql • :offset • :join_table • :uniq • :dependent ROR Lab.
  • 23. Association Options belongs_to options has_one options has_many options HABTM options • :autosave • :autosave • :autosave • :autosave • :class_name • :class_name • :class_name • :class_name • :conditions • :conditions • :conditions • :conditions • :foreign_key • :foreign_key • :foreign_key • :foreign_key • :include • :include • :include • :include • :readonly • :readonly • :readonly • :readonly • :select • :select • :select • :select • :validate • :validate • :validate • :validate • :dependent • :as • :as • :order • :counter_cache • :order • :order • :counter_sql • :polymorphic • :primary_key • :primary_key • :extend • :touch • :source • :source • :finder_sql • :source_type • :source_type • :group • :through • :through • :limit • :dependent • :counter_sql • :offset • :extend • :uniq • :finder_sql • :association_foreign_key • :group • :delete_sql • :limit • :insert_sql • :offset • :join_table • :uniq • :dependent ROR Lab.
  • 24. Association Options belongs_to options has_one options has_many options HABTM options • :autosave • :autosave • :autosave • :autosave • :class_name • :class_name • :class_name • :class_name • :conditions • :conditions • :conditions • :conditions • :foreign_key • :foreign_key • :foreign_key • :foreign_key • :include • :include • :include • :include • :readonly • :readonly • :readonly • :readonly • :select • :select • :select • :select • :validate • :validate • :validate • :validate • :dependent • :as • :as • :order • :counter_cache • :order • :order • :counter_sql • :polymorphic • :primary_key • :primary_key • :extend • :touch • :source • :source • :finder_sql • :source_type • :source_type • :group • :through • :through • :limit • :dependent • :counter_sql • :offset • :extend • :uniq • :finder_sql • :association_foreign_key • :group • :delete_sql • :limit • :insert_sql • :offset • :join_table • :uniq • :dependent ROR Lab.
  • 25. Association Options belongs_to options has_one options has_many options HABTM options • :autosave • :autosave • :autosave • :autosave • :class_name • :class_name • :class_name • :class_name • :conditions • :conditions • :conditions • :conditions • :foreign_key • :foreign_key • :foreign_key • :foreign_key • :include • :include • :include • :include • :readonly • :readonly • :readonly • :readonly • :select • :select • :select • :select • :validate • :validate • :validate • :validate • :dependent • :as • :as • :order • :counter_cache • :order • :order • :counter_sql • :polymorphic • :primary_key • :primary_key • :extend • :touch • :source • :source • :finder_sql • :source_type • :source_type • :group • :through • :through • :limit • :dependent • :counter_sql • :offset • :extend • :uniq • :finder_sql • :association_foreign_key • :group • :delete_sql • :limit • :insert_sql • :offset • :join_table • :uniq • :dependent ROR Lab.
  • 26. Association Options belongs_to options has_one options has_many options HABTM options • :autosave • :autosave • :autosave • :autosave • :class_name • :class_name • :class_name • :class_name • :conditions • :conditions • :conditions • :conditions • :foreign_key • :foreign_key • :foreign_key • :foreign_key • :include • :include • :include • :include • :readonly • :readonly • :readonly • :readonly • :select • :select • :select • :select • :validate • :validate • :validate • :validate • :dependent • :as • :as • :order • :counter_cache • :order • :order • :counter_sql • :polymorphic • :primary_key • :primary_key • :extend • :touch • :source • :source • :finder_sql • :source_type • :source_type • :group • :through • :through • :limit • :dependent • :counter_sql • :offset • :extend • :uniq • :finder_sql • :association_foreign_key • :group • :delete_sql • :limit • :insert_sql • :offset • :join_table • :uniq • :dependent ROR Lab.
  • 27. Association Options belongs_to options has_one options has_many options HABTM options • :autosave • :autosave • :autosave • :autosave • :class_name • :class_name • :class_name • :class_name • :conditions • :conditions • :conditions • :conditions • :foreign_key • :foreign_key • :foreign_key • :foreign_key • :include • :include • :include • :include • :readonly • :readonly • :readonly • :readonly • :select • :select • :select • :select • :validate • :validate • :validate • :validate • :dependent • :as • :as • :order • :counter_cache • :order • :order • :counter_sql • :polymorphic • :primary_key • :primary_key • :extend • :touch • :source • :source • :finder_sql • :source_type • :source_type • :group • :through • :through • :limit • :dependent • :counter_sql • :offset • :extend • :uniq • :finder_sql • :association_foreign_key • :group • :delete_sql • :limit • :insert_sql • :offset • :join_table • :uniq • :dependent ROR Lab.
  • 28. Association Options belongs_to options has_one options has_many options HABTM options • :autosave • :autosave • :autosave • :autosave • :class_name • :class_name • :class_name • :class_name • :conditions • :conditions • :conditions • :conditions • :foreign_key • :foreign_key • :foreign_key • :foreign_key • :include • :include • :include • :include • :readonly • :readonly • :readonly • :readonly • :select • :select • :select • :select • :validate • :validate • :validate • :validate • :dependent • :as • :as • :order • :counter_cache • :order • :order • :counter_sql • :polymorphic • :primary_key • :primary_key • :extend • :touch • :source • :source • :finder_sql • :source_type • :source_type • :group • :through • :through • :limit • :dependent • :counter_sql • :offset • :extend • :uniq • :finder_sql • :association_foreign_key • :group • :delete_sql • :limit • :insert_sql • :offset • :join_table • :uniq • :dependent ROR Lab.
  • 29. Association Options belongs_to options has_one options has_many options HABTM options • :autosave • :autosave • :autosave • :autosave • :class_name • :class_name • :class_name • :class_name • :conditions • :conditions • :conditions • :conditions • :foreign_key • :foreign_key • :foreign_key • :foreign_key • :include • :include • :include • :include • :readonly • :readonly • :readonly • :readonly • :select • :select • :select • :select • :validate • :validate • :validate • :validate • :dependent • :as • :as • :order • :counter_cache • :order • :order • :counter_sql • :polymorphic • :primary_key • :primary_key • :extend • :touch • :source • :source • :finder_sql • :source_type • :source_type • :group • :through • :through • :limit • :dependent • :counter_sql • :offset • :extend • :uniq • :finder_sql • :association_foreign_key • :group • :delete_sql • :limit • :insert_sql • :offset • :join_table • :uniq • :dependent ROR Lab.
  • 30. Common Options • :autosave • :class_name • :conditions • :foreign_key • :include • :readonly • :select • :validate ROR Lab.
  • 31. - common options - :autosave • No declaration (default) : new children are saved when their parent is saved • :autosave => true : all children is saved, no matter whether they are new records • :autosave => false : any children is not saved ROR Lab.
  • 32. - common options - :autosave class Post has_one :author, :autosave => true end has_one post = Post.find(1) post.title # => "The current global position of migrating ducks" post.author.name # => "alloy" post.title = "On the migration of ducks" post.author.name = "Eloy Duran" post.save post.reload post.title # => "On the migration of ducks" post.author.name # => "Eloy Duran" post.author.mark_for_destruction post.author.marked_for_destruction? # => true id = post.author.id Author.find_by_id(id).nil? # => false post.save post.reload.author # => nil Author.find_by_id(id).nil? # => true http://api.rubyonrails.org/classes/ActiveRecord/AutosaveAssociation.html ROR Lab.
  • 33. - common options - :autosave has_many class Post has_many :comments # :autosave option is no declared end post = Post.new(:title => 'ruby rocks') post.comments.build(:body => 'hello world') post.save # => saves both post and comment post = Post.create(:title => 'ruby rocks') post.comments.build(:body => 'hello world') post.save # => saves both post and comment post = Post.create(:title => 'ruby rocks') post.comments.create(:body => 'hello world') post.save # => saves both post and comment class Post has_many :comments, :autosave => true end post = Post.create(:title => 'ruby rocks') post.comments.create(:body => 'hello world') post.comments[0].body = 'hi everyone' post.save # => saves both post and comment, with 'hi everyone' as body post.comments.last.mark_for_destruction post.comments.last.marked_for_destruction? # => true post.comments.length # => 2 id = post.comments.last.id Comment.find_by_id(id).nil? # => false post.save post.reload.comments.length # => 1 Comment.find_by_id(id).nil? # => true ROR Lab.
  • 34. - common options - :class_name class Order < ActiveRecord::Base   belongs_to :customer, :class_name => "Patron" end ROR Lab.
  • 35. - common options - :conditions class Order < ActiveRecord::Base   belongs_to :customer, :conditions => "active = 1" end ROR Lab.
  • 36. - common options - :foreign_key class Order < ActiveRecord::Base   belongs_to :customer, :class_name => "Patron",     :foreign_key => "patron_id" end ROR Lab.
  • 37. - common options - :include class LineItem < ActiveRecord::Base   belongs_to :order, :include => :customer end   class Order < ActiveRecord::Base   belongs_to :customer   has_many :line_items end   class Customer < ActiveRecord::Base   has_many :orders end ROR Lab.
  • 38. - common options - :readonly class Customer < ActiveRecord::Base   has_many :orders, :readonly => true end ROR Lab.
  • 39. - common options - :select class Order < ActiveRecord::Base   belongs_to :customer, :select => "name, profile, group_id" end ROR Lab.
  • 40. - common options - :validate class Order < ActiveRecord::Base   belongs_to :customer, :validate => true end ROR Lab.
  • 41. Common has_ Options has_one / has_many • :as • :order* (also, included in HABTM) • :primary_key • :source • :source_type • :through ROR Lab.
  • 42. - common has_ options - :as class Picture < ActiveRecord::Base   belongs_to :imageable, :polymorphic => true end   class Employee < ActiveRecord::Base   has_many :pictures, :as => :imageable end   class Product < ActiveRecord::Base   has_many :pictures, :as => :imageable end ROR Lab.
  • 43. - common has_ options - :order class Post < ActiveRecord::Base   has_many :comments, :order => ”updated_at” end •also, in HABTM ROR Lab.
  • 44. - common has_ options - :primary_key class Order < ActiveRecord::Base default   belongs_to :customer, :primary_key => "id", :foreign_key => "customer_id" class Order < ActiveRecord::Base   belongs_to :customer, :class_name => "Patron", :primary_key => "civil_no", :foreign_key => "patron_id" ROR Lab.
  • 45. - common has_ options - :source & :source_type class Tag < ActiveRecord::Base has_many :taggings, :dependent => :destroy has_many :books, :through => :tagings, :source => :taggable, :source_type => "Book" has_many :movies, :through => :tagings, :source => :taggable, :source_type => "Movie" end class Tagging < ActiveRecord::Base belongs_to :taggable, :polymorphic => true belongs_to :tag end class Book < ActiveRecord::Base has_many :taggings, :as => :taggable has_many :tags, :through => :taggings end class Movie < ActiveRecord::Base has_many :taggings, :as => :taggable has_many :tags, :through => :taggings end • http://www.brentmc79.com/posts/polymorphic-many-to-many-associations-in-rails ROR Lab.
  • 46. - common has_ options - :through class Supplier < ActiveRecord::Base   has_one :account   has_one :account_history, :through => :account end   class Account < ActiveRecord::Base   belongs_to :supplier   has_one :account_history end   class AccountHistory < ActiveRecord::Base   belongs_to :account end ROR Lab.
  • 47. Common _many Options has_many / HABTM • :counter_sql • :extend • :finder_sql • :group • :limit • :offset • :uniq ROR Lab.
  • 48. - common _many options - :finder_sql class Person < ActiveRecord::Base has_many :subscribers, :class_name => "Person", :finder_sql => Proc.new { %Q{ SELECT DISTINCT * FROM people p, post_subscriptions ps WHERE ps.post_id = #{id} AND ps.person_id = p.id ORDER BY p.first_name } } ROR Lab.
  • 49. - common _many options - :counter_sql class Person < ActiveRecord::Base has_many :subscribers, :class_name => "Person", :counter_sql => Proc.new { %Q{ SELECT DISTINCT * FROM people p, post_subscriptions ps WHERE ps.post_id = #{id} AND ps.person_id = p.id ORDER BY p.first_name } } ROR Lab.
  • 50. - common _many options - :extend association proxy(or interface) class Customer < ActiveRecord::Base   has_many :orders do     def find_by_order_prefix(order_number)       find_by_region_id(order_number[0..2])     end   end ROR Lab.
  • 51. - common _many options - :extend module FindRecentExtension   def find_recent     where("created_at > ?", 5.days.ago)   end end   class Customer < ActiveRecord::Base   has_many :orders, :extend => FindRecentExtension end   class Supplier < ActiveRecord::Base   has_many :deliveries, :extend => FindRecentExtension ROR Lab.
  • 52. - common _many options - :extend class Customer < ActiveRecord::Base   has_many :orders,     :extend => [FindRecentExtension, FindActiveExtension] end ROR Lab.
  • 53. - common _many options - * 3 AP accessors • proxy_association.owner • proxy_association.reflection • proxy_association.target AP* : Association Proxy ROR Lab.
  • 54. - common _many options - :group class Customer < ActiveRecord::Base   has_many :line_items, :through => :orders, :group => "orders.id" end ROR Lab.
  • 55. - common _many options - :limit / :offset class Customer < ActiveRecord::Base   has_many :recent_orders, :class_name => "Order",      :order => "order_date DESC", :limit => 100 :offset => 300 ROR Lab.
  • 56. - common _many options - :uniq class Person < ActiveRecord::Base   has_many :readings   has_many :posts, :through => :readings end   person = Person.create(:name => 'john') post   = Post.create(:name => 'a1') person.posts << post person.posts << post person.posts.inspect # => [#<Post id: 5, name: "a1">, #<Post id: 5, name: "a1">] Reading.all.inspect  # => [#<Reading id: 12, person_id: 5, post_id: 5>, #<Reading id: 13, person_id: 5, post_id: 5>] ROR Lab.
  • 57. - common _many options - :uniq class Person   has_many :readings   has_many :posts, :through => :readings, :uniq => true end   person = Person.create(:name => 'honda') post   = Post.create(:name => 'a1') person.posts << post person.posts << post person.posts.inspect # => [#<Post id: 7, name: "a1">] Reading.all.inspect  # => [#<Reading id: 16, person_id: 7, post_id: 7>, #<Reading id: 17, person_id: 7, post_id: 7>] ROR Lab.
  • 58. Common one-way Options belongs_to / has_one / has_many • :dependent class Comment < ActiveRecord::Base   belongs_to :post, :dependent => :destroy end class Post < ActiveRecord::Base   has_many :comments, :dependent => :destroy end ROR Lab.
  • 59. Special Options • belongs_to • :counter_cache • :polymorphic • :touch • HABTM • :association_foreign_key • :delete_sql • :insert_sql • :join_table ROR Lab.
  • 60. - special options for HABTM - :association_foreign_key class User < ActiveRecord::Base   has_and_belongs_to_many :friends, :class_name => "User",     :foreign_key => "this_user_id",     :association_foreign_key => "other_user_id" many-to-many self join ROR Lab.
  • 61. - special options for HABTM - :delete_sql class Developer < ActiveRecord::Base has_and_belongs_to_many :active_projects, :join_table => 'developers_projects', :delete_sql => "DELETE FROM developers_projects WHERE active=1 AND developer_id = #{id} AND project_id = #{record.id}" end ROR Lab.
  • 62. - special options for HABTM - :insert_sql class Developer < ActiveRecord::Base has_and_belongs_to_many :active_projects, :join_table => 'developers_projects', :insert_sql => "INSERT INTO developers_projects VALUES(#{id},#{record.id})" end ROR Lab.
  • 63. - special options for HABTM - :join_table class Category < ActiveRecord::Base   has_and_belongs_to_many :products, :join_table => “cats_prods” end   class Product < ActiveRecord::Base   has_and_belongs_to_many :categories, :join_table => “cats_prods” default join table => “categories_products” ROR Lab.
  • 64. Association Callbacks • in the lifecycle of a collection • before_add • after_add • before_remove • after_remove ROR Lab.
  • 65. Association Callbacks class Customer < ActiveRecord::Base   has_many :orders, :before_add => :check_credit_limit     def check_credit_limit(order)     ...   end end class Customer < ActiveRecord::Base   has_many :orders,     :before_add => [:check_credit_limit, :calculate_shipping_charges]     def check_credit_limit(order)     ...   end     def calculate_shipping_charges(order)     ...   end ROR Lab.
  • 68.   ROR Lab.

Notas do Editor

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n
  67. \n
  68. \n
  69. \n
  70. \n