More Rails- ActiveRecord, ActionController, ActionView, and .ppt
《More Rails- ActiveRecord, ActionController, ActionView, and .ppt》由会员分享,可在线阅读,更多相关《More Rails- ActiveRecord, ActionController, ActionView, and .ppt(35页珍藏版)》请在麦多课文档分享上搜索。
1、More Rails: ActiveRecord, ActionController, ActionView, and if time, Associations,Administrivia,Armando/Will office hours moved to Thursdays 1:30 Lab will be staffed for up to 30 mins. after most classes Well try to work more labs into the class time starting next week,Active Record: what is it?,A c
2、lass library that provides an object-relational model over a plain old RDBMS Deal with objects & attributes rather than rows & columns SELECT result rows enumerable collection (later) object graph join query,SQL 101 (Structured Query Language),Relational model of data organization (Codd, 1969) based
3、 on predicate logic & set theory Theoretical model implemented by Gray et al. in 1970s portable language (structured query language, SQL) to express relational operations relational database stores the data and provides transactional semantics to instantiate the abstract relational model Think of a
4、table as an unordered collection of objects that share a schema of simply-typed attributes eg: Student = Think of SELECT as picking some records out SELECT lastname,ucb_sid FROM students WHERE degree_expected 12/31/07 Generally,SELECT attribs FROM tables WHERE constraints Joins are more interesting,
5、 well do them later,While were on SQL. whats a primary key anyway?,Column whose value must be unique for every table row Why not just use (e.g.) last name or SID#? SQL AUTO_INCREMENT function makes it easy to specify an integer primary key If using migrations to create tables (recommended), Rails ta
6、kes care of creating an autoincrement primary key field called ID,CREATE TABLE students ( id INT NOT NULL AUTO_INCREMENT, last_name VARCHAR(255), first_name VARCHAR(255), ucb_sid INT(11) DEFAULT 9999 );,class CreateStudentsfalse, :default=9999 end enddef self.down drop_table :students end end,A Rela
7、tional Database System is a “SQL Server“,Maintains tables, accepts SQL queries, returns results API varies (embedded library, socket, etc.) RDBMS servers maintain ACID properties Atomicity: all or nothing Consistency: like a single copy Isolation: transactions that execute simultaneously & touch sam
8、e tables dont interfere with each other Durability: changes are “sure” once committed Very hard to get engineering for this correct with high performance = Oracle = $,MySQL vs. SQLite,Command line interface Various GUIs: MySQLAdmin, PHPMyAdmin, CocoaMySQL (MacOS).,Local file,Your app,SQLite library,
9、DB#1,DB#n,Server process,Server process,SQL commands,results, , ,filesystem calls,Review: CRUD,4 basic operations on a table row: Create, Read, Update attributes, Destroy INSERT INTO students (last_name, ucb_sid, degree_expected) VALUES (“Fox”, 99999, “1998-12-15”), (“Bodik”, 88888, “2009-06-05”) SE
10、LECT * FROM students WHERE (degree_expected “2000-01-01”) UPDATE students SET degree_expected=“2008-06-05” WHERE last_name=“Bodik”) DELETE FROM students WHERE ucb_sid=99999,More on Student Example,object attributes are “just” instance methods (a la attr_accessor) so can already say stu.last_name, st
11、u.ucb_sid, etc. what line in what file makes this happen? ActiveRecord accessors/mutators default attr_accessor for each table column perform type-casting as needed can be overridden, virtualized, etc.,Example: a short tour,Predicate-like method names often end with question mark,self (like Java thi
12、s) not strictly necessary here,Interpolation of expressions into strings,Some useful class methods of Date,Constructors,Method named initialize, but invoked as new (at least) 3 ways to call it.,New != Create,Call s.save to write the object to the database s.create(args) s.new(args); s.save s.update_
13、attributes(hash) can be used to update attributes in place s.new_record? is true iff no underlying database row corresponds to s save does right thing in SQL (INSERT or UPDATE) Convention over configuration: if id column present, assumes primary key if updated_at/created_at columns in table, automat
14、ically are set to update/creation timestamp,find() SQL SELECT,# To find an arbitrary single record: s = Student.find(:first) # returns a Student instance # To find all records: students = Student.find(:all) # returns enumerable!# find by id primary key (Note! throws RecordNotFound) book = Book.find(
15、1235) # Find a whole bunch of things ids_array = get_list_of_ids_from_somewhere() students = Student.find(ids_array)# To find by column values: armando = Student.find_by_last_name(Fox) # may return nil a_local_grad = Student.find_by_city_and_degree_expected(Berkeley, Date.parse(June 15,2007)# To fin
16、d only a few, and sort by an attribute many_localgrads = Student.find_all_by_city_and_degree_expected(Berkeley, Date.parse(June 15,2007),:limit=30,:order=:last_name) ,Find by conditions,Use ? for values from parameters. Rails will sanitize the SQL and prevent any SQL injectionYou will want to learn
17、some minimal SQL syntax,# Using SQL conditions books = Book.find(:all, :conditions = pub_date between ? and ?, params:start_date, params:end_date, :order = pub_date DESC),You can also specify ordering and use arbitrary SQL operators:,Find by conditions,Use ? to substitute in condition values not man
18、datory, but a good idea!You can include other SQL functionalityYou can roll your own s = Student.find_by_sql(“SELECT * FROM students .“),# Using SQL conditions books = Book.find(:all, :conditions = pub_date between ? and ?, params:start_date, params:end_date, :order = pub_date DESC),Advanced Find,bo
19、oks = Book.find(:all, :conditions = pub_date between ? and ?, params:start_date, params:end_date,:limit = 10, :offset = params:page.to_i * 10),You can also specify limits and offsets, and oh so much more,:lock - Holds lock on the records (default: share lock) :select - Specifies columns for SELECT (
- 1.请仔细阅读文档,确保文档完整性,对于不预览、不比对内容而直接下载带来的问题本站不予受理。
- 2.下载的文档,不会出现我们的网址水印。
- 3、该文档所得收入(下载+内容+预览)归上传者、原创作者;如果您是本文档原作者,请点此认领!既往收益都归您。
下载文档到电脑,查找使用更方便
2000 积分 0人已下载
下载 | 加入VIP,交流精品资源 |
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- MORERAILSACTIVERECORD ACTIONCONTROLLER ACTIONVIEW ANDPPT

链接地址:http://www.mydoc123.com/p-373015.html