Skip to content

Instantly share code, notes, and snippets.

@pobing
Last active August 29, 2015 14:24
ruby tips 1
#flatten.uniq 去数组中的重复元素
@my_orgunits = (current_user.orgunits + current_user.groups+ current_user.watch_open_groups).flatten.uniq
# use db
ActiveRecord::Base.connection.execute("use db")
# gsub
Mblog.find_each do |mblog|
unless mblog.content.nil?
mblog.content=mblog.content.gsub(/\[(\w+)\]/) do |c|
emotions[$1]
end
mblog.save
end
end
# match,regexp
phone_regexp=/\A\d{3,4}-\d{7,8}\z|\A\d{3,4}-\d{7,8}-\d{1,3}\z|\A\d{3,15}\z|\A\d{7,8}-\d{1,3}\z/
user.phone.present? and phone_regexp.match(user.phone).nil?
#模型保存时取消验证
if user.save(:validate=>false)
render_json_ok
else
render :json => { errors: user.error }
end
#将一个string 数组,附加给 一个整形数组 ,将 ["1","2","3"] 转化为[1,2,3]
a = []
b = ["1","2","3"]
b.each {|x| a.push(x.to_i)}
# validate ,if ,on
validates :name, :presence => {message: "名称不能为空"}, :uniqueness => {message: "名称已经存在" , :if=>:same_parent, :on=>:create},
:length => { maximum: 20 , message: "名称过长,最长为20个字符" }
protected
def same_parent
self.class.exists?(:name=>self.name,:parent_id=>self.parent_id)
end
# 正则匹配电话号码
validates :phone, :format => { with: /\A\d{3,4}-\d{7,8}\z|\A\d{3,4}-\d{7,8}-\d{1,3}\z|\A\d{3,15}\z|\A\d{7,8}-\d{1,3}\z/ ,message: "电话号码只允许包含'-'和数字" },
:allow_blank => true
# when case
ext =
case ext1
when ".wpt" then ".doc"
when ".ett" then ".xls"
when ".dpt" then ".ppt"
else ext1
end
# rake db add version
rake db:migrate VERSION=20080906120000
# where in
SELECT * from orgunits as o where id in (select orgunit_id from members as m where o.id = m.orgunit_id and m.user_id=2 and m.status=1) and otype<=2
# rais migration index
rails migration add index
add_index(:watchers, [:watchable_type, :watchable_id,:user_id], :unique => true)
add_index(:taggings, [:tag_id, :taggable_type, :taggable_id], :unique => true)
add_index(:likes, [:item_type, :item_id, :user_id], :unique => true)
remove_index :likes, :name=>:index_likes_on_item_type_and_item_id
remove_index :taggings, :name=>:index_taggings_on_taggable_type_and_taggable_id
remove_index :watchers, :name=>:index_watchers_on_watchable_type_and_watchable_id
# ! ?
!current_org.is_member?(current_user)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment