rails 小技艺

rails 小技巧
#Rails Tip 1 Actions Are Methods http://errtheblog.com/posts/1-actions-are-methods
class PostsController < ApplicationController
  def list_by_author
    list :conditions => ['author_id = ?', params[:id]] 
  end

  def list(find_options = {})
    @posts =  Post.find(:all, { :order => 'created_on desc' }.merge(find_options))
    render :action => :list
  end
end

技术要点:
对浏览器传过来的Hash表 params 进行加工处理,使用Hash.merge技术调用Post.find方法,使得list_by_month, list_by_year变得多余。

#Rails Tip 2 Real Console Helpers 在console中使用 ApplicationHelperhttp://errtheblog.com/posts/41-real-console-helpers
#假设我们有这样一个applicationHelper
module ApplicationHelper
  def application_helper_method
    true
  end
end
#如果直接在 在 rails console中,是不起作用的。
>> helper.application_helper_method =>NoMethodError: undefined method `application_helper_method'       
#正确的方法是
helper.extend ApplicationHelper  => #<Object:0x2572f68>
helper.application_helper_method => true

#Rail Tip 3 分类组织好Model Organize Your Models 
http://errtheblog.com/posts/3-organize-your-models
Rails::Initializer.run do |config|
  config.frameworks -= [ :action_web_service ]
  config.load_paths += %W[
    #{RAILS_ROOT}/app/models/api
    #{RAILS_ROOT}/app/models/cache
    #{RAILS_ROOT}/app/models/database
    #{RAILS_ROOT}/app/models/tableless
  ]
end
技术要点:通过这种方法,我们将model 分成了几个部分 models/api  models/tableless ... 当然,以上代码,直接用 config.load_paths += Dir[”#{RAILS_ROOT}/app/models//“] 更简洁。


#Rail Tip 4 Accessor Missing” http://errtheblog.com/posts/18-accessor-missing
这是一篇非常重要文章,解释了模型中的belongs_to :author 以及 attribute accessor(例如story模型是的title)是如何工作。
结论:
1、belongs_to is a class method of ActiveRecord::Base。When belongs_to is called,It’s a real method defined on my Story class. 
belong_to 是ActiveRecord::Base中的类方法,当Story类被加载,程序运行到 belongs_to :author的时候,author(),author=(),被定义在 Strory类。 

2、假设Author表中有一个title列。那个 title(),title=()这两个Get/set方法是如何出现的呢。它们是method_missing。并不真实存在于Article类中。
3、通过alise(别名),可以提供belong to 产生的方法再封装
  class Story < ActiveRecord::Base
    belongs_to :author

    alias :real_author :author
    def author
      auth = real_author
      auth.name
    end
  end