Rails中隐藏的特性,技巧--不断更新中......

Friday, July 16, 2010

1,为了避免重复提交表单,rails中的submit_tag很好的选项disable_with

submit_tag "提交", :disable_with => "提交中..."

当用户按下"提交"按钮将会禁止再次点击提交,按钮就会变成"提交中...",
2, 把数字转成序数词像1st,2nd, 3rd, 4th.

1.ordinalize = "1st"

3,
在rails的model中,生产环境中是缓存类的,比如一个Country模型中定义一个常量表示所有的国家(当model加载的时候将会做Country.all查询)

class Country < ActiveRecord::Base
  COUNTRIES = self.all
....
end

你可以在试图中使用这个常量, 比如

<%= select_tag(:country, options_for_select(Country::COUNTRIES)) %>

4, 在environment.rb你可以自定义时间和日期的格式

[Time::DATE_FORMATS, Date::DATE_FORMATS].each do |obj|
  obj[:dots] = "%m.%d.%y"
end

在视图中就可以用了

Created: <%= @my_object.created_at.to_s(:dots) %>

打印出来将是 Created: 07.16.10

5, 返回do 。。。。end这个块的处理结果 是个returning xxx 的这个xxx对象, 不知道有没理解错

def returns_a_hash(id)
  returning Hash.new do |result|
    result["id"] = id
  end
end

6, 典型的用法在many-to-one时,当many端发生改变时,更新one端的updated_at时间,
touch选项给个true就可以了

class Post < ActiveRecord::Base
  has_many :replies
end

class Reply < ActiveRecord::Base
  belongs_to :post, :touch => true
end

7, Use Paperclip interpolations: file config/initializers/paperclip.rb:

module Paperclip
  module Interpolations
    def user_id(attachment, style)
      current_user.id
    end
  end
end


has\_ attached\_file option:


:url => "/assets/:user_id/:id/:style/:filename"

(The syntax changed from Paperclip 2.x to 2.3; :path is not necessary;
Use the latest version and have a look at the source, it's quite well
documented.)

8, 在Observer中访问session

class MyObserverClass < ActiveRecord::Observer
  cattr_accessor :current_user # GLOBAL VARIABLE. RELIES ON RAILS BEING SINGLE THREADED
other logging code goes here
end


class ApplicationController
  before_filter :set_current_user_for_observer
def set_current_user_for_observer
    MyObserverClass.current_user = session[:user]
  end
end

9, 合并AR中的条件

condition1 = ['name like ?','Hnery%']
condition2 = ['state = ?','draft']
Member.first(:conditions => Member.merge_conditions(condition1,condition2))

ref:
merge_conditions

10, 在AR的find方法中使用symbol

Account.find(:all, :conditions => ['name LIKE :name AND updated_at < :date', {:name => "aname", :date => 3.days.ago}])

11, 在AR中使用distinct

Item.find( :all, :select => 'DISTINCT fieldname' )

12,Use ActionController helper_method,hide_action methods

class BookController < ActionController::Base
def category_name
 "RubyOnRails"
end

hide\_action :category\_name \#you can't visit action category\_name.

helper\_method :category\_name \#you can call 'category\_name' in view

end

This entry was tagged hidden-features and Rails

comments powered by Disqus

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

go to Top