50 %
50 %
Information about Rails-activerecord

Published on February 26, 2015

Author: russel_05

Source: slideshare.net

1. Active Record in Rails by Farhan Faruque

2. Topics ❏ Basics ❏ Active Record Migrations ❏ Active Record Validations

3. Active Record- What? ❏ an ORM (Object Relational Mapping). ❏ a layer of Ruby code that runs between your database and your logic code.

4. Convention over Configuration ● if you configure your applications in the very same way most of the time then this should be the default way ● Database Table - Plural with underscores separating words (e.g., book_clubs). ● Model Class - Singular with the first letter of each word capitalized (e.g., BookClub). Model/class Table / Schema BookClub book_clubs Post Posts

5. Creating Active Record Models Model class Post < ActiveRecord::Base attr_accessor :title,:desc end Database CREATE TABLE Posts ( id int(11) NOT NULL auto_increment, title varchar(255), desc text, PRIMARY KEY (id) );

6. CRUD: Reading and Writing Data Create post = Post.create(title: ‘Cricket WC’,desc:’2015 Australia’) Read post = Post.all # return a collection with all users post = Post.where(title:’Cricket WC’) Update post = Post.find_by(title:’Cricket WC’) post.desc = ‘Cricket World cup - 2015’ post.save delete post.destroy

7. Migrations - Basic ❏ Alter Database and Schema in a consistent way ❏ database independent ❏ each migration as being a new 'version' of the database

8. Migration - Example $ rails generate model location name:string description:text class CreateLocation < ActiveRecord::Migration def change create_table :location do |t| t.string :name t.text :description t.timestamps null: false end end end

9. Creating Migration $ rails generate migration AddStreetToLocations street:string class AddStreetToLocation< ActiveRecord::Migration def change add_column :locations, :street, :string end end ● stored as files in the db/migrate directory ● The name of the file is of the form YYYYMMDDHHMMSS_add_street_to_location.rb

10. Migration - convention Convention Example Generates in Change AddXXXToXXX AddStreetToLocation street:string add_column :locations, :street, : string RemoveXXXFromXXX RemoveStreetFromLocation street: string remove_column :location, street : string CreateXXX CreateLocation create_table :location XXXRefToXXX AddCountryRefToLocation add_reference :Location, :country, index: true XXXJoinTableXXX CreateJoinTableCustomerProduct customer product create_join_table :customers, : products

11. Changing table and column change_column :location, :latitude, :string change_table :products do |t| t.remove :description, :name end

12. Migration - Passing Modifiers $ bin/rails generate migration AddDetailsToProducts 'price:decimal{5,2}' class AddDetailsToProducts < ActiveRecord::Migration def change add_column :products, :price, :decimal, precision: 5, scale: 2 end end Modifiers Type ● limit ● required ● default ● etc..

13. Using the up/down Methods ❏ same as change method ❏ used before rails-3.1 ❏ up method use for transformation ❏ down method for revert up

14. Running Migration ❏ $ rake db:migrate - run current migration ❏ $ rake db:migrate VERSION=20080906120000 - run specific version ❏ $ rake db:rollback - roll back to previous version ❏ $rake db:migrate RAILS_ENV=test - run migration in test environement

15. Active Record Validations - Why? ❏ ensures valid data ❏ model-level validation

16. Others ways of validations problems ❏ Database Constraints - database dependent ❏ Client-side validations - unreliable ❏ Controller-level validations - difficult to test and maintain

17. Example class Location < ActiveRecord::Base validates :name, presence: true end Person.create(name: "John Doe").valid? # => true Person.create(name: nil).valid? # => false

18. Validation triggers ❏ create ❏ create! ❏ save ❏ save! ❏ update ❏ update!

19. Validations Helpers ❏ acceptance class Person < ActiveRecord::Base validates :terms_of_service, acceptance: true end ❏ confirmation class Person < ActiveRecord::Base validates :email, confirmation: true end

20. Other Validations Helpers ❏ length ❏ numericality ❏ validates_associated ❏ exclusion ❏ format ❏ presence ❏ uniqueness ❏ etc..

21. Common options :allow_nil :allow_blank :message :on

22. Conditional Validation :if and :unless ❏ a symbol :a method name ❏ a string :a really short condition ❏ a proc :an inline condition Example - with a method class Order < ActiveRecord::Base validates :card_number, presence: true, if: :paid_with_card? def paid_with_card? payment_type == "card" end end

23. Custom Validations ❏ Inherited from Two moudles ➢ ActiveModel::Validator ➢ ActiveModel::EachValidator ➢ get the ‘record’ argument as parameter ❏ Custom method and helpers

24. Working with Validation Errors ❏ errors.messages ❏ errors[:attr] # for a specific attribute ❏ errors.add(:attr,message) ❏ errors[:base] #object’s state as a whole ❏ errors.clear #clear errors ❏ errors.size #count of errors

25. Displaying Validation in Views

#clear presentations

Add a comment

Related pages

Rails’ Active Record - GitHub · Where software is built

Hier sollte eine Beschreibung angezeigt werden, diese Seite lässt dies jedoch nicht zu.
Read more

ActiveRecord::Base - Ruby on Rails

Active Record. Active Record objects don't specify their attributes directly, but rather infer them from the table definition with which they're linked.
Read more

Ruby on Rails: ActiveRecord: CRUD – Wikibooks, Sammlung ...

In diesem Kapitel schauen wir uns die CRUD-Funktionen der Datebankabstraktionsschicht von Rails, ActiveRecord, an. Jetzt erfahren wir also endlich, wie wir ...
Read more

Ruby on Rails: ActiveRecord: Validierung – Wikibooks ...

Was passiert, wenn sich jemand bei unserem neuen Hyper-Duper-Service registriert und vergisst den Benutzernamen anzugeben? Was, wenn er beim Newsletter in ...
Read more

ActiveRecord::Base - APIdock - Front page - APIdock

Active Record. Active Record objects don’t specify their attributes directly, but rather infer them from the table definition with which they’re linked.
Read more

ActiveRecord - APIdock

The docs you’re looking for are in ActiveRecord::Base. Welcome; Register; Projects; Help; About; Blog; APIdock release: IRON STEVE (1.4)
Read more

ActiveRecord::FinderMethods - Ruby on Rails API

Module ActiveRecord::FinderMethods activerecord/lib/active_record/relation/finder_methods.rb; Methods. E. exists? F. fifth, fifth!, find ...
Read more

ruby on rails - ActiveRecord OR query - Stack Overflow

How do you do an OR query in Rails 3 ActiveRecord. All the examples I find just have AND queries. Edit: without using a SQL string!
Read more

ruby on rails - ActiveRecord::PendingMigrationError ...

How to resolve Rails ActiveRecord::PendingMigrationError? 0 ... ActiveRecord::PendingMigrationError Migrations are pending. To resolve this issue, ...
Read more

OpenLink ODBC Adapter for Ruby on Rails / Active Record

RubyForge Could Not Connect to Database: RubyForge Could Not Connect to Database:
Read more