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) 

在我的特殊情況下,該沒問題,因爲我不需要所有存儲過程的值,現在只能查詢它我需要它的案例。

希望這可以幫助其他人。 :)