2012-06-27 73 views
5

我正在使用Ruby on Rails 3.2.2,我想知道是否在範圍方法中,只有當表尚未加入時,纔有可能「動態」加入表。它,我有:僅當該表尚未加入時纔可以「動態」加入表?

def self.scope_method_name(user) 
    joins(:joining_association_name).where("joining_table_name.user_id = ?", user.id) 
end 

我想提出類似如下:

# Note: the following code is just a sample in order to understand what I mean. 
def self.scope_method_name(user) 
    if table_is_joined?(joining_table_name) 
    where("joining_table_name.user_id = ?", user.id) 
    else 
    joins(:joining_association_name).where("joining_table_name.user_id = ?", user.id) 
    end 
end 

是否有可能/宜作呢?如果是這樣,我怎麼能/應該繼續?


我想用這種方法,以避免multiple database table statements in INNER JOIN of SQL queries在某些情況下,似乎使我的SQL查詢,因爲多個表的語句無法按預期工作)等使用scope_method_name而無需關心相關的SQL查詢問題(在我的情況下,不關心連接數據庫表)。

:它可以提高SQL錯誤(例如,錯誤,樣「ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'joining_table_name.user_id' in 'where clause'」),當你有沒有加入尚未數據庫表(例如,當你喜歡ClassName.scope_method_name(@user)運行的代碼,這可能發生沒有以前加入joining_association_name等沒有加入相關joining_table_name表)。

回答

-1

方法loaded?在哪裏檢查是否已加載關聯。你可以嘗試使用它。

if association_name.loaded? 
    where("joining_table_name.user_id = ?", user.id) 
else 
    joins(:joining_association_name).where("joining_table_name.user_id = ?", user.id) 
end 
+0

請問你的代碼避免SQL錯誤(例如,錯誤,類似「你在你的SQL語句的錯誤:表'joining_table_name'沒有在SQL查詢中指定或該表中不存在的數據庫「)*數據庫表(例如,當您像'ClassName.scope_method_name(@user)'*一樣運行代碼時可能會發生這種情況*以前不加入* join_association_name',因此不加入相關的'joining_table_name'表)? – user12882

+0

對不起,我剛剛看到您正在嘗試使用示波器。 'association_name.loaded?'只適用於一個實例。不能回答你的問題...但鐵軌應該照顧不加載一次關聯兩次。 – spas

+0

看來,Rails不關心「兩次加載關聯」,至少在[鏈接的問題]的情況下(http://stackoverflow.com/questions/11210241/what-means-happens-when -using-the-inner-join-with-multiple-database-table-st?lq = 1)(閱讀評論)。 – user12882