2

我继承了一个 Rails 2.2.2 应用程序并被要求将其升级到 Rails 3.2,所以我出去并在旧 Rails 2.2.2 项目的复制版本中运行脚本 git://github.com/rails/rails_upgrade.git目录,以便我可以随时进行更改。

我正在处理 ActiveRecord 查询,使用新的 Rails 3 更改所有即将弃用的 ActiveRecord 调用,如 find(:all)、find(:first)、带条件的查找和 :joins 选项ActiveRecord API 语法。

我一直在看这里,但是我需要转换为新语法的一些查询没有示例,所以我尽力弄清楚它们可能是什么。

有人可以告诉我我是否在正确的轨道上进行以下更改?

谢谢

示例 1

 #### Rails 2.x.x version
 @users = B2bUser.find(:all, :order => "name", :order => "#{params[:sort]} #{params[:direction]}")

 #### Rails 3.x.x version
 @users = B2bUser.order("name","#{params[:sort]} #{params[:direction]}")

示例 2

 ### should work for both Rails 2.x and Rails 3.x
 @user = B2bUser.find(params[:id])

 #### Or is this better?
 @user = B2bUser.where("id = ?",params[:id])


 #### Rails 2.x.x version
 @privileges = B2bPrivilege.find(:all, :conditions => "b2b_user_id = #{@user.id}")

 ### Rails 3.x.x version
 @privileges = B2bPrivilege.where("b2b_user_id =  ?",@user.id)

示例 3

 #### Rails 2.x.x version
@privileges = B2bPrivilege.find(:all, :conditions => "b2b_user_id = #{@user.id}", :joins => "LEFT JOIN vendors ON vendors.id = b2b_privileges.vendor_id", :select => "b2b_privileges.*, vendors.name AS vendor_name", :order => "vendors.name")

#### Rails 3.x.x version 
@privileges = B2bPrivilege.find_by_sql( "SELECT b2b_privileges.*, vendors.name AS vendor_name FROM b2b_privileges LEFT JOIN vendors ON vendors.id = b2b_privileges.vendor_id WHERE b2b_user_id = ?  ORDER BY vendors.name", @user.id)

示例 4

    #### Rails 2.x.x version
    @vendor_list = Vendor.find(:all, :conditions => "is_active = 'YES'", :order => "name", :select => "id, name")

    #### Rails 3.x.x version
    @vendor_list = Vendor.find_by_sql("SELECT id, name FROM vendors WHERE is_active = 'YES' ORDER BY name")

示例 5

 #### Rails 2.x.x version
 @existing = B2bPrivilege.find(:first, :conditions => "b2b_user_id = #{@user.id} AND vendor_id = #{params[:add_vendor][:id]}", :select => "id")

 #### Rails 3.x.x version   
 @existing = B2bPrivilege.find_by_sql("SELECT id FROM b2b_privileges WHERE b2b_user_id = ? AND vendor_id = ? LIMIT 1",@user.id,params[:add_vendor][:id])
4

1 回答 1

2

示例 3、4 和 5 应使用wherelimitselect方法构建。

@vendor_list = Vendor.where(:is_active => 'YES')
                     .select(:id, :name)
                     .order(:name)
@existing = B2bPrivilege.where(b2b_user_id => params[:add_vendor], vendor_id => params[:id])
                        .select(:id)
                        .limit(1)

除此之外,我认为你正在做一个漂亮而干净的实现。

于 2013-02-18T16:35:46.310 回答