24 Sep 2009

rails中的ActiveRecord真性感!

Rails使用的ActiveRecord真性感啊,see see吧

class User < ActiveRecord::Base  
  has_many :articles  
end  
 
class Article < ActiveRecord::Base
  belongs_to :user  
end

然后执行
>> Article.find(1) 会得到延迟加载user对象的sql语句。如下:

SELECT * FROM articles WHERE (articles.id =1) LIMIT 1

当需要访问user对象时,比如用article.user.name会再生成一个sql语句请求数据库。
如果执行
>> Article.find(1,:include => :user) 会得到一次性加载了user的查询

SELECT
articles.`extended_html` AS t0_r6 articles.`excerpt` AS t0_r7
articles.`keywords` AS t0_r8 articles.`allow_pings` AS t0_r10
articles.`allow_comments` AS t0_r9 users.`id` AS t1_r0
articles.`published` AS t0_r11 users.`login` AS t1_r1
articles.`text_filter` AS t0_r12 articles.`id` AS t0_r0
users.`password` AS t1_r2 articles.`user_id` AS t0_r13
articles.`title` AS t0_r1 users.`name` AS t1_r3
articles.`created_at` AS t0_r14 articles.`author` AS t0_r2
users.`email` AS t1_r4 articles.`updated_at` AS t0_r15
articles.`body` AS t0_r3 articles.`permalink` AS t0_r16
articles.`body_html` AS t0_r4 articles.`guid` AS t0_r17
articles.`extended` AS t0_r5
FROM articles LEFT OUTER JOIN users
ON users.id = articles.user_id
WHERE (articles.id = 1)

是不是很优美,很性感涅?