首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > 其他数据库 >

rails base 之数据库-查询

2012-09-14 
rails base 之数据库---查询a Category.new(:name Ruby, :position 1)a.save# save 还有相同方

rails base 之数据库---查询

a = Category.new(:name => 'Ruby', :position => 1)a.save# save 还有相同方法”save!”# 有无惊叹号的差别在于validate资料验证不正确的动作,# 无惊叹号版本会回传布林值(true或false),有惊叹号版本则是验证错误会丢出例外。b = Category.create(:name => 'Perl', :position => 2)# create也有“create!”方法,作用同save# create在执行的时候已经将资料插入数据库,无须再调用save方法b.save(:validate => false)# 透过:valiate => false 可以略过验证# create虽然无需再调用save方法,但仍然可以调用save方法。Category.first# 取出第一条记录Category.last# 取出最后一条记录Category.all# 取出所有Category.find(1)# 取出id=1的记录Category.find(1, 3)Category.find([1, 3])# 取出id为1和3的记录# find方法会在没有取到符合条件的记录时抛出错误# 如果你不想这样,请用:find_by_idCategory.find_by_name('Ruby')# 取出name字段等于“Ruby”的记录# 可以用and进行多字段查询Category.find_by_name_and_postion('Ruby', 1)# 取出name='ruby' and postion=1的记录# find_by_* 和 find_all_by_*它们的不同之处是前者会进行“limit 1”限制Category.find_by_sql("SELECT * FROM categories WHERE name LIKE '%p%'")# 如果你想自己手写sql就可以使用这个方法# find_by_sql没有“find_all_by_sql”方法Category.where(:name => 'Ruby', :position => 1)# `name` = 'Ruby' AND `position` = 1Category.where(["name = ? or position = ?", 'Ruby', 3])# `name` = 'Ruby' OR `position` = 3# 另外,where 是lazy loading,也就是直到真的需要取值的时候,才会跟资料库拿资料。# 如果需要立即触发,可以接着使用.all, .first, .last,例如:# Category.where(["name = ? or position = ?", 'Ruby', 3]).allCategory.limit(5).all# 限制查询记录数,它只接受这一个参数# 如果要使用形如:“limit x, y"请组合使用“offset”方法Category.order("position")Category.order("position DESC")Category.order("position DESC, name ASC")# 对内容排序Category.order("position").reorder("name")# 改用name 排序Category.order("position").reorder(nil)# 取消所有排序Category.limit(3).offset(2)# 从第二条开始显示3条记录Category.select('id, name')# 只查询出id,name栏位的数据Category.readonly.first# 使用readonly可以使查询出来的结果不能再次改变其值# 以上查询方法可以进行无顺序的自由的串接:# Category.select(..).order(..).limit(.)....Category.where("position > 1").find_each do |category|  category.do_some_thingend# 如果资料量很大,但是又需要全部拿出来处理,可以使用find_each 批次处理Category.find_each(:batch_size => 2) do |category|  puts category.idend# 预设会批次查出1000条,如果需要设定可以加上:batch_size 参数。c = Category.allc.reload# reload 重新查询出结果给cc = Category.firstc.destory# 删除id = c.id的资料Category.delete(2)# 删除id = 2的资料Category.count# 获取记录总数Category.average(:position)Category.maximum(:position)Category.sum(:position)# 略过...Category.where(["position>?", 2]).count# 用where缩小范围c = Category.firstc.update_attributes(:position => 6)# or# 注意下边这个,我照书上抄的,老是报错,好像不行,试着传hast,array,symbol都不行# 版本 3.1.0c.update_attributes('position', 6)# 更新id = c.id的记录使栏柆position=6# 同类方法:“update_attributes!”a = Order.select("*,sum(price) as p,count(*) as c").where("a=? ",2).group("date_format(created_at,'%Y-%m')")#select 指定要查询的字段#group 分组# date_format mysql中的时间格式化

热点排行