随笔-167  评论-65  文章-0  trackbacks-0

rails ActiveRecord 操作数据库(CRUD)


Create:

添加记录
(1) new 和 save
user = User.new
user.name = value1
user.password = value2
user.save


(2) create 下面增加了两条记录
User.create([{:name=>value1,:password=>value2},{:name=>value3,:password=>value4}])


使用 块  作为构造参数 添加记录
User.new do |f|
f.name = value1
f.password = value2
f.save
end


使用 Hash对象 作为构造参数 添加记录
user=User.new(
:name=>value1,
:password=>value2
)
user.save

 

Delete:

删除记录
message = Message.find(params[:id]) #找到该message对象,ruby的变量是随时可以变的,而且可以直接作为对象变量
message.destroy

Update:


更新记录
@message = Message.update(params[:id],:detail=>params[:message][:detail])
其中params[:id] 取得的是主键id,由表单提交时的 :id参数传过来

 

ClientInfo.update_all("password ="+"'"+password.to_s+"'","email= "+"'"+email.to_s+"'");


        update_all(" status = '1' ",
        "client_info_id = #{id} and status = 0"
        )


 find(:first,:conditions=>["client_id=? and name='投资组合'",value1]).update_attributes(
        :status=>value2)


Order.find(12).update_attributes(:name => "Barney", :email => "barney@bedrock.com")

根据条件update

ref:

http://dev.rubyonrails.org/ticket/5961



Search:


根据一个字段指定的名称查询
mymessage = Message.find(:all,:conditions=>["user_id=?",session[:user_id]])
查询messages表中user_id为session[:user_id]值的对象

 


根据主键的id查询
user = User.find(1)
查询users表中主键id为1的User对象
user.name 即可得到该对象的name值
user.password 即可得到该对象的password值


查询两个字段
User.find(:all,:conditions=>["name=? and password=?",name,password])

 


查询全部记录
User.find(:all) 或者 User.all

取得某一对象name字段值
User.find(params[:id]).name


Select :

根据 id 查询 数据记录集

      vo = Post.find :all , :conditions => ["type = 'BlogPost' "]
      vo2 = Comment.find :all , :conditions => ["commentable_type = 'Post' "]     
      Activity.find(:all,
     :conditions => ["activities.item_id in (?) and item_type = 'Post' or activities.item_id in (?) and item_type = 'Comment' ",vo.map(&:id).uniq , vo2.map(&:id).uniq],
        :order => 'activities.created_at DESC',
        :limit => GLOBAL_FEED_SIZE
      )

上述查询结果为 : select 出 activities表的item_type = Post 并且 item_id 在vo记录集 中 加上 item_type = Comment 并且 item_id 在vo2记录集 中,

ref:

http://www.spacevatican.org/2008/4/29/include-and-conditions


 

 

 


待续.............


write by feng
posted on 2009-03-20 19:03 fl1429 阅读(1345) 评论(0)  编辑  收藏 所属分类: Rails

只有注册用户登录后才能发表评论。


网站导航:
 
已访问数:
free counters