【译】Rails中的两个小技巧

Wednesday, August 4, 2010

原文:http://developer.idapted.com/2010/08/04/rails-small-tips/

1. flash 和 flash.now

flash在rails中用来做消息提示, 它是使用session来完成这个功能。

def create

  if User.authorize(params[:login], params[:password])
    flash[:notice] = "login success"
    redirect_to target_path
  else
    flash[:error] = "login fail"
    render :new
  end
end

flash[:notice]在redirect_to后产生效果,在这个例子中, 如果登录失败,
错误消息将不会显示在“new”模板中,会在下一个调转页面中, 当我们使用render时候应该用flash.now
flash.now[:notice]将在当前页面生效,即在new页就能看到错误消息

2.select 和 include

Rails的ActiveRecord的finder的 “select”选项在用 “include”预先加载关联记录集时不能正常工作

class Student < ActiveRecord::Base
   has_one :call
end

class Call < ActiveRecord::Base
   belongs_to :student
end

我们要查询Student对象的Call对象的updated_at 优化前:

@students = Student.all(:include => [:call], :select=> "students.id, students.login, students.called_times, calls.updated_at as last_called_at")

这里依然预先加载了“call” 而且返回了一个完整记录 优化后:

#include eql left outer join
@students = Student.all(:select => "students.id, students.login, students.called_times,
calls.updated_at as last_called_at", :joins => "left outer join calls on students.id = calls.student_id")

现在,我们只从students表取了我们需要的字段

This entry was tagged Rails and tips

comments powered by Disqus

© 2009-2013 lxneng.com. All rights reserved. Powered by Pyramid

go to Top