2008年7月31日 星期四

named_scope

http://ryandaigle.com/articles/2008/3/24/what-s-new-in-edge-rails-has-finder-functionality

class User < ActiveRecord::Base
named_scope :registered, lambda { |time_ago| { :conditions => ['created_at > ?', time_ago] } }
end

class User < ActiveRecord::Base

named_scope :inactive, :conditions => {:active => false} do
def activate
each { |i| i.update_attribute(:active, true) }
end
end
end
# Re-activate all inactive users
User.inactive.activate


named_scope

http://pivots.pivotallabs.com/users/nick/blog/articles/284-hasfinder-it-s-now-easier-than-ever-to-create-complex-re-usable-sql-queries
http://ryandaigle.com/articles/2008/3/24/what-s-new-in-edge-rails-has-finder-functionality

has_finder and scope_out are instead of named_scope
class User < ActiveRecord::Base
named_scope :registered, lambda { |time_ago| { :conditions => ['created_at > ?', time_ago] }
named_scope :has_registered, lambda {|*args| { :conditions => ['created_at > ?', (args.first || 2.weeks.ago)]}}
named_scope :adult, :include => :profile, :conditions => {'profiles.adult' => true}
end
還可以設預設值喔
User.registered 7.days.ago # same as User.find(:all, :conditions => ['created_at > ?', 7.days.ago])


class User < ActiveRecord::Base
named_scope :inactive, :conditions => {:active => false} do
def activate
each { |i| i.update_attribute(:active, true) }
end
end
end
# Re-activate all inactive users
User.inactive.activate

# Store named scopes
active = User.scoped(:conditions => {:active => true})
recent = User.scoped(:conditions => ['created_at > ?', 7.days.ago])

# Which can be combined
recent_active = recent.active

# And operated upon
recent_active.each { |u| ... }

def find_records(result)
scope = Record.scoped({})
scope = scope.scoped :conditions => ["records.success = ?", result] unless result.blank?
scope
end

2008年7月29日 星期二

logger rails

From within a controller, model or mailer:
logger.info "Starting process fubar..."

logger rails

alias_method_chain, alias_method

http://hooney.javaeye.com/blog/210244

alias_method_chain
想要改變原來function的method 內容, 又想要保留原來的method內容
可以用

alias_method :old_a, :a
alias_method :a, :modified_a

這樣就是改 modified_a, 叫a 就會變了
這樣不用動a的內容, 想要叫之前的a 就是叫old_a

可是這樣太麻煩 可以直接用 alias_method_chain 會幫妳自動產生些function

alias_method_chain :foo, :feature
替我們定義了兩個方法:foo_with_feature 和 foo_without_feature <保存原來的foo方法>

def foo_with_feature
在此添加想向foo方法裡面寫的代碼
foo_without_feature 調用一下原來的方法
end

check model has this method


respond_to? 判斷是不是model是不是有這個method

User.respond_to?("name") => true

User.respond_to?("abc") => false

2008年7月24日 星期四

observe_field, with

http://api.rubyonrails.org/classes/ActionView/Helpers/PrototypeHelper.html#M001633

with 那邊的parameter還可以用prototype 去get 其他element的value

<%= observe_field :target_type_target_type_id,
:update => :target_list,
:on => "change",
:url => {:action => :update_target_list},
:with => "{target_type_id: value, target_cat_id: $('target_type_target_cat_id').value}"%>

update, replace_html

http://api.rubyonrails.org/classes/ActionView/Helpers/PrototypeHelper/JavaScriptGenerator/GeneratorMethods.html#M001645
replace_html可以用partial 去取代

render :update do |page|
page.replace_html 'target_type_target_type_id',
:partial => 'target_type_select', :locals => {:types => target_type_content}
end

2008年7月20日 星期日

find random offset

http://blog.pbg4.org/2008/1/2/find-randomly-redux
http://wiki.rubyonrails.org/rails/pages/HowtoSelectRandomRecords
http://groups.google.com/group/Ruby-on-Rails-Taiwan/browse_thread/thread/27ec511fa258ca08
http://blog.commonthread.com/2007/12/7/tip-ruby-on-rails-random-array-element

目前一般的最佳解是這個, random 出offest
def self.find(*args)
scope = args.first
if scope.to_s == "random"
super :first, :offset => (rand count).to_i
elsif scope.to_s == "public"
# blah, blah...
else
super
end
end
ps:console下
Record.find(:first, :offset => (rand Record.count).to_i)

要用Record.count, sometimes some record would be deleted
ps2:bad way find(rand(count) + 1) rescue ActiveRecord::RecordNotFound random

array, some functions


a = [ "a", "b", "c" ]
a.index("b") #=> 1
a.index("z") #=> nil
a.index{|x|x=="b"} #=> 1
This is an alias of find_index.

a = [ 11, 22, 33, 44 ]
a.fetch(1) #=> 22
a.fetch(-1) #=> 44
a.fetch(4, 'cat') #=> "cat"
a.fetch(4) { |i| i*i } #=> 16

a = [ "q", "r", "s", "t" ]
a.first #=> "q"
a.first(1) #=> ["q"]
a.first(3) #=> ["q", "r", "s"]


ar = [:a, :b, :c]
>> ar.slice(0..-1)
=> [:a, :b, :c]
>> ar.slice(0..1)
=> [:a, :b]

[ "a", "b" ].concat( ["c", "d"] ) #=> [ "a", "b", "c", "d" ]

ary = [1, 2, 4, 2]
ary.count # => 4
ary.count(2) # => 2
ary.count{|x|x%2==0} # => 3


[ "a", "b", "c" ].join #=> "abc"
[ "a", "b", "c" ].join("-") #=> "a-b-c"

[ "w", "x", "y", "z" ].last #=> "z"

[ "a", "b", "c" ].reverse #=> ["c", "b", "a"]

a = [ "a", "b", "c" ]
a.reverse_each {|x| print x, " " }
produces:
c b a

a = [ "d", "a", "e", "c", "b" ]
a.sort #=> ["a", "b", "c", "d", "e"]
a.sort {|x,y| y <=> x } #=> ["e", "d", "c", "b", "a"]

a = [ "a", "a", "b", "b", "c" ]
a.uniq #=> ["a", "b", "c"]

a.values_at(-1, -3, -5, -7)
a.values_at(1..3, 2...5)

2008年7月17日 星期四

create table, column


def self.up
create_table :mugshots do |t|
t.column :user_id, :integer
t.column :created_at, :datetime
t.column :parent_id, :integer
t.column :content_type, :string
t.column :filename, :string
t.column :thumbnail, :string
t.column :size, :integer
t.column :width, :integer
t.column :height, :integer
end
end

CREATE TABLE `mugshots` (`id` int(11) DEFAULT NULL auto_increment
PRIMARY KEY, `user_id` int(11) DEFAULT NULL NULL, `created_at`
datetime DEFAULT NULL NULL, `parent_id` int(11) DEFAULT NULL NULL,
`content_type` varchar(255) DEFAULT NULL NULL, `filename`
varchar(255) DEFAULT NULL NULL, `thumbnail` varchar(255) DEFAULT
NULL NULL, `size` int(11) DEFAULT NULL NULL, `width` int(11) DEFAULT
NULL NULL, `height` int(11) DEFAULT NULL NULL) ENGINE=InnoDB

sql, alter, change the database character

http://dev.mysql.com/doc/refman/5.1/en/alter-database.html
http://dev.mysql.com/doc/refman/5.1/en/alter-table.html
ALTER DATABASE db_name DEFAULT CHARACTER SET utf8

http://dev.mysql.com/doc/refman/5.1/en/show-create-table.html
http://dev.mysql.com/doc/refman/5.1/en/show-create-database.html
show create table alert_targets;

jquery, corner

http://malsup.com/jquery/corner/

<script type='text/javascript'>
$(function() {
$('.rounded').corner();
});
</script>

javascript history

http://www.techotopia.com/index.php/JavaScript_History_Object
http://www.exforsys.com/tutorials/javascript/javascript-history-object-properties-and-methods.html
<a href="javascript:history.go(-1)">back</a>

script defer

http://blog.guoshuang.com/?p=2964
http://www.imleon.cn/article.asp?id=479

IE專屬讓script 在整個頁面最後load完才load

Time, 想把秒數直接弄成幾天幾分幾秒

#at 從1970年1月1日後 幾秒鐘的時間
#at 直接拿到的是local time, 還要用getgm換成gmtime 就可以了
>> Time.at(10000).getgm
=> Thu Jan 01 02:46:40 UTC 1970


>> Time.gm(2000)
=> Sat Jan 01 00:00:00 UTC 2000
>> Time.mktime(2000)
=> Sat Jan 01 00:00:00 +0800 2000
>> Time.mktime(2000).getgm
=> Fri Dec 31 16:00:00 UTC 1999

sql, not, <>, in

User.find(:all, :conditions => ["id not in (?)",[2,3,5]]).map(&:id)
id <>(?)
not = <>

group


Record.find(:all, :select => "user_id, sum(todo_time) as sum", :group => 'user_id').map(&:sum)
SELECT user_id, sum(todo_time) as sum FROM `records` GROUP BY user_id

Record.find(:all, :select => "user_id, sum(todo_time)", :group => 'user_id').map(&:'sum(todo_time)')
SELECT user_id, sum(todo_time) FROM `records` GROUP BY user_id

Record.find(:all, :select => "user_id, count(*) as count", :group => 'user_id').map {|u| [u.user_id, u.count]}
SELECT user_id, count(*) as count FROM `records` GROUP BY user_id

capture, content_for

http://api.rubyonrails.org/classes/ActionView/Helpers/CaptureHelper.html

如果你想改layout的東西, 可是又只想是在某個controller/action下去做變動, 除了在
layout判斷controller.controller_name 和 controller.action_name之外, 還
有另外一個選擇, 那就是capture

[某個action]
<% @header = capture do %>
<%= link_to "#{@user.name}的早起紀錄",{:controller => 'main', :action => 'index'} ,:class => 'ebhead'%>
<% end %>

因為只有在這個action view裡, @header才會產生

就可以直接在layout裡去看這個variable在不在, 不用在那邊判斷controller name, action name
<% if @header %>
<%= @header %>
<% else %>
<a href='<%= home_url %>'> 早&nbsp;鳥&nbsp;&nbsp;<span >i wake la</span> </a>
<% end %>