rails 小技巧

[color=blue]#Rails Tip 1 Actions Are Methods http://errtheblog.com/posts/1-actions-are-methods[/color]
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变得多余。

[color=blue]#Rails Tip 2 Real Console Helpers 在console中使用 ApplicationHelperhttp://errtheblog.com/posts/41-real-console-helpers
[/color]
#假设我们有这样一个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

[color=blue]#Rail Tip 3 分类组织好Model Organize Your Models[/color]
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//“] 更简洁。


[color=blue]#Rail Tip 4 Accessor Missing” http://errtheblog.com/posts/18-accessor-missing[/color]
这是一篇非常重要文章,解释了模型中的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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值