0

我想在ActiveRecord一个has_one关系的查询来选择附加字段选择选项。在使用Lambda:的HAS_ONE关系

的问题是:选择查询的内容必须每选择查询点火时间进行评估,因为我得到一个存储过程的附加字段的值,我需要在运行时传递参数。

我会想象它这样莫名其妙地工作:

class User < ActiveRecord::Base 

    has_one :profile, :select => lambda { "SELECT profiles.*, my_stored_procedure(#{Time.now}) as virtual_attribute" } 

end 

我不能使用的范围,因为我需要使用预取上includes父模型这种关系:

User.includes(:profile).find(1,2,3) 

也作为二级预取型号:

OtherModel.includes(:user => [ :profile ]) 

回答

0

我的解决方案

我发现的一个可能的解决方案是对模型进行子类化并覆盖default_scope,这也可能占用一个块。我已经测试过它,它按预期工作!

但要注意,这只能在Rails 3.1,作为3.0接受为default_scope方法块(它们只是被忽略)是很重要的。

这里是所涉及的车型的一个例子:

class Other < ActiveRecord::Base 

    has_many :users 

end 


class User < ActiveRecord::Base 

    has_one :profile 
    has_one :profile_with_relationship 

end 


class Profile < ActiveRecord::Base 
end 


class ProfileWithRelationship < Profile 

    set_table_name "profiles" 

    default_scope do 
    select("'#{Time.now}' as virtual_attribute") 
    end 

end 

现在它甚至嵌套包括:

Other.includes(:users => :profile_with_relationship).find(1) 

会产生:

Other Load (0.1ms) SELECT "others".* FROM "others" WHERE "others"."id" = ? LIMIT 1 [["id", 1]] 
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."other_id" IN (1) 
ProfileWithRelationship Load (0.2ms) SELECT '2011-11-23 11:34:15 +0100' as virtual_attribute, "profiles".* FROM "profiles" WHERE "profiles"."user_id" IN (1, 2, 3, 4, 5) 

在我的特殊情况下,该没问题,因为我不需要所有存储过程的值,现在只能查询它我需要它的案例。

希望这可以帮助其他人。 :)