Rails持久层的解决方案
插入记录:
1.调用new()和save()
不使用任何构造参数调用new()
- def add_new_record
- book=Book.new
- book.bookName=params[:book][:bookname]
- book.author=params[:book][:author]
- if book.save then
- redirect_to:action=>'list'
- else
- render:action=>'new'
- end
- end
使用块作为构造参数调用new()
- def add_newblock_record
- Book.new do |book|
- book.bookName=params[:book][:bookname]
- book.author=params[:book][book:author]
- book.save
- end
- redirect_to:action=>'list'
使用Hash对象作为构造参数调用new()
- book=Book.new(
- :bookName=>params[:book][:bookname],
- :author=>params[:book][:author]
- )
- if book.save then
- redirect_to:action=>'list'
- else
- render:action=>'newhash'
- end
2.调用create()方法增加记录
用create()增加单行记录
- def create_record
- book=Book.create(
- :bookname=>params[:book][:bookname]
- :author=>params[:book][:author]
- redirect_to:action=>'list'
- )
- end
用create()增加多行记录
- def craete_records
- book.Book.create(
- {:bookname=>params[:book][:bookname1],
- :author=>params[:book][:author1]},
- {:bookname=>params[:book][:bookname2],
- :author=>params[:book][:author3]}
- )
- redirect_to:action=>'list'
- end
查询记录
强大的find()
根据id查询:find(id)
查询第一行记录:find(:first,options)
查询全部:find(:all,options) /find_all
find_by_id :find(1),find(1,2),find([3,4])
find_by_属性名:find_by_bookname(’test’)
find_all_by_属性名:find_all_by_author(’jiang’)
find_by_属性1_and_属性2:find_by_bookname_and_author(’test’,'jiang’)
find_all_by_属性1_and_属性2:find_all_by_bookname_and_author(’test’,'jiang’)
find_by_sql:find_by_sql(”select * from books”)
查看和检验持久化对象的属性
attributes()查询对象的属性
attribute_names()查询对象的属性名字
attribute_present?()查询是否包含指定的属性
统计记录
使用count()
统计所有记录:User.count
条件统计:User.count(’age>18′)
使用count_by_sql
Book.count_by_sql(”select count(*) from books where author=’jiang”)
更新记录
直接更新记录
- user=User.find(1)
- user.username="jiang"
- user.save
用find_by_sql查询时,必须包含主键列
使用update_attribute/update_attributes
update_attribute(name,value)
update_attributes(attributes)
- user=User.find(1)
- user.update_attribute(:username,'jiang')
- user.update_attributes({"username"=>'jiang',"password"=>'12345"})#如果传送的Hash对象中指定更新主键,则会被忽略
使用update/update_all更新记录
update(id,attributes)
- User.update(2,{"username"=>'jiang',"password"=>"12345"})
更新多条记录
- ids=[]
- ids<<1
- ids<<2
- atts=[]
- atts<<{"username"=>'jiang',"password"=>"12345"}
- atts<<{"username"=>'zhang',"password"=>"54321"}
- User.update(ids,atts)
使用update_all更新记录
- User.update_all(["if_available=?",0],["account_balanace<=?",0])
第一个是set后的参数,第二个是where后的字符串
update set if_availiable=0 where account_balanace<=0
删除记录
使用delete根据主键删除
User.delete(1)
User.delete(params[:ids])
使用delete_all根据条件删除
User.delete_all(["if_dimission=?",1])
相当于delete from users where if_dimission=1
使用destroy根据主键删除
User.find(1).destroy
使用destroy_all根据条件删除
User.destroy_all(["if_dimission=?",1])
使用destroy时,先调用这些持久化对象相关的回调和校验方法,更安全,但效率慢
数据库中表的关联关系
has_one
has_many
belongs_to
has_and_belongs_to_many
Leave a comment
您必须 登录 后才能发表留言。