每天一剂Rails良药之Manage a Static Site With Rails
对于静态站点我们可以利用Rails的cache来管理,如在controller中添加如下代码: after_filter {|c| c.cache_page} 这样将会对该controller的所有action作缓存 注意我们不要对UserProfile等页面做缓存,只对对所有用户一样的内容做缓存
每天一剂Rails良药之Write Code That Writes Code
很不幸我的2006-4-11版本的Rails Recipes的这章内容部分缺失 太晚了又没有找到更新的版本 记为not finished.
每天一剂Rails良药之Convert Your Sessions To ActiveRecord
我们看看config/environment.rb文件,其中有以下一段: # Use the database for sessions instead of the file system # (create the session table with 'rake db:sessions:create') # config.action_controller.session_store = : ...
每天一剂Rails良药之Stud Out Authentication
登录和认证常常是我们Rails系统所必需的,但经常不是程序的核心功能 我们可以在ApplicationController里定义logged_in?方法: def logged_in? local_request? end helper_method :logged_in? 这样我们就可以在我们的Rails系统中的任何地方使用logged_in?方法 而且我们简单的用local_request? ...
每天一剂Rails良药之Make your URLs Meaningful(and pretty)
这篇内容没什么价值,《Agile Rails》里的Routing Request一节讲述的比较详细了 ActionController::Routing::Routes.draw do |map| map.connect ':controller/service.wsdl', :action => 'wsd' map.connect ':controller/:action/:id' map ...
每天一剂Rails良药之Rendering CSV From Your Actions
有时候我们需要输出Comma Separated Values(CSV)等各种形式的输出来满足用户的需要: class ExportController < Application ontroller def orders content_type = if request.user_agent =~ /windows/i 'application/vnd.ms-excel' else 't ...
每天一剂Rails良药之Keep An Eye On Your Session Expiry
Rails的session默认为当用户关闭浏览器时终止 我们可以在config/environment.rb里设置它: CGI::Session.expire_after 1.month 这需要一个插件,具体session设置请参考http://wiki.rubyonrails.org/rails/pages/HowtoChangeSessionOptions 这不是今天我们讨论的重点 出于安 ...
每天一剂Rails良药之Cleaning Up Controllers with Post-back Actions
我们习惯与one-action-per-request,但是我们(特别是初学者)很容易被controller里的new(),create(),edit()和update()这些方法弄晕。 其实我们可以用一个方法来代替them all: def edit @recipe = Recipe.find_by_id(params[:id]) || Recipe.new if request.post? @ ...
每天一剂Rails良药之Role-Based Authorization
我们的系统往往并不只是靠登录这么简单来控制权限,今天我们来看看基于角色的授权 假设我们的系统已经建立了昨天的users表 1,migration class AddRolesAndRightsTables < ActiveRecord::Migration def self.up create_table :users_roles, :id => false do |t| t.col ...
每天一剂Rails良药之Authentication
今天我们来看看Rails怎么处理登录认证 虽然Rails有很多登录认证的插件,但是我们可以自己动手丰衣足食 1,db/migrate/001_add_user_table.rb class AddUserTable < ActiveRecord::Migration def self.up create_table :users do |t| t.column :username, :st ...
每天一剂Rails良药之Safely Use Models in Migrations
我们平时做Migrations时除了更改schema,还经常需要更改data 但我们以前的Migrations可能不工作,因为data之间可能有依赖关系 我们可以通过在Migrations里定义Model来解决该问题: class AddPositionToProducts < ActiveRecord::Migration class Product < ActiveRecord:: ...
每天一剂Rails良药之Make Dumb Data Smart with composed_of
ActiveRecord有一个composed_of()方法用来声明组件关系,如: class Person < ActiveRecord::Base composed_of :address, :class_name => "Address", :mapping => [%w(address_street street), %w(address_city c ...
每天一剂Rails良药之DRY Up Your ActiveRecord Code With Scoping
Rails真的是在搜肠刮肚挖空心思想方设法的给代码减肥瘦身,这次我们来看看with_scope方法 class PostsController < ApplicationController before_filter :scope_posts_to_user def show @posts = Post.find(:all) end def create @post = Post.crea ...
每天一剂Rails良药之Perform Calculations on Your Model Data
ActiveRecord::Calculations模块提供了model级的方法来得到model数据的count,sum,average,maximum和minimum值 例如: Person.count("age > 21") Person.average(:age) Person.minimum(:age) Person.maximum(:age) Person.av ...
Rails宝典八十五式:YAML配置文件
我们的程序中可能有一些参数配置,我们可以将这些配置放在外部YAML文件里而不必污染应用程序代码: # config/initializers/load_config.rb APP_CONFIG = YAML.load_file("#{RAILS_ROOT}/config/config.yml")[RAILS_ENV] # application.rb def authentic ...
Rails宝典八十四式:Cookie Based Session Store
Rails 2.0将默认使用CookieStore来存储session数据,这符合SNA,很好 如果从Rails 1.x迁移到Rails 2.0,需要这样配置一下: # in environment.rb Rails::Initializer.run do |config| config.action_controller.session = { :session_key => '_stor ...
Rails宝典八十三式:Migrations in Rails 2.0
Migrations are now sexy in Rails 2.0! 创建当前environme的数据库 rake db:create 创建所有environme的数据库 rake db:create:all 创建和修改Model script/generate model task name:string priority:integer script/generate mi ...
Rails宝典八十二式:Rails 2.0之HTTP Basic Authentication
# products_controller.rb before_filter :authenticate protected def authenticate authenticate_or_request_with_http_basic do |username, password| username == "foo" && password == " ...
Rails宝典八十一式:Rails2.0之Fixtures尝鲜
Rails 2.0中Fixtures简单多了,看个例子: # products.yml couch: name: Couch price: 399.99 manufacturer: lazyboy categories: furniture tv_stand: name: TV Stand price: 149.95 manufacturer: highdeph categories: furni ...
Rails宝典八十式:Rails 2.0简化视图
Rails 2.0 里视图应该怎样写? views/products/index.html.erb: <%= render :partial => @products %> views/products/show.html.erb: <%= render :partial => @product %> _product.html.erb: < ...
Rails宝典七十九式:生成Named Routes
我们有如下三个近乎一样的named routes: # routes.rb ActionController::Routing::Routes.draw do |map| map.about_company 'about/company', :controller => 'about', :action => 'company' map.about_company 'about/pri ...
Rails宝典七十八式:生成PDF文档
1,install gem install pdf-writer 2,require & register # environment.rb require 'pdf/writer' Mime::Type.register 'application/pdf', :pdf 3,use # lib/product_drawer.rb def self.draw(products) ...
Rails宝典七十七式:禁止JavaScript时的Destroy
Rails里一般我们这样Destroy: <%= link_to "Destroy", project_path(project), :confirm => "Are you sure?", :method => :delete %> 但是当客户端浏览器禁止JavaScript时就呆了,没有confirm,直接给删除了 所以如果我们 ...
Rails宝典七十六式:使用scope_out插件
安装 ruby script/plugin install http://scope-out-rails.googlecode.com/svn/trunk/ 使用例子 # models/task.rb scope_out :incomplete, :conditions => ['complete=?', false], :order => 'name' # tasks_cont ...
Rails宝典之七十五式:复杂表单Part3
前两次学习了动态添加和删除project的多个tasks,这次来看看如何编辑project 其他页面不变,但是_task.rhtml改了: <!-- projects/edit.rhtml --> <% form_for :project, :url => project_path(@project), :html => { :method => 'put' ...
Rails宝典之七十四式:复杂表单Part2
这次来看看如何使用JavaScript和RJS来动态添加和删除表单域: 继续上次的例子,我们首先要在layout里引入Prototype.js <%= javascript_include_tag :defaults %> 然后是新建project的页面模板: <div id="tasks"> <%= render :partial =&g ...
Rails宝典七十三式:复杂表单Part1
来看一个典型的场景,Project这个Model的new表单,我们需要在创建Project对象时也创建一些Task对象 我们可以使用fields_for这个标签: <!-- new.rhtml --> <% form_for :project, :url => projects_path do |f| %> <p> Name: <%= f.text ...
Rails宝典七十二式:添加自己的Environment
Rails自带了development、test和production三个environments,而我们可以轻松添加自己的environment: 1,修改database.yml staging: adapter: mysql database: store_staging user: root password: host: localhost 2,添加enviromnets/stagi ...
Rails宝典七十一式:用RSpec测试你的Rails程序
Rails宝典七十一式:用RSpec测试你的Rails程序 Rails虽然自带有Controller、Model、Integration的测试框架,但是用起来感觉很枯燥无味 所以,你应该试试RSpec+Mocha这道纯正的墨西哥菜 RSpec is a framework which provides programmers with a Domain Specific Language to ...
Rails宝典之七十式: 自定义Routes
我们希望按如下url来查看articles archive: http://localhost/articles http://localhost/articles/2007 http://localhost/articles/2007/9 http://localhost/articles/2007/9/28 我们可以这样定义routes: # in routes.rb map.connect ...