2010-08-16 19 views
0

在我的Rails應用中,我有一個has_many關係的類。爲了提高效率,我想直接使用SQL來更新數據庫中的許多行,然後我想將has_many關係標記爲不再有效。如果後面的代碼訪問has_many關係,我希望它重新加載數據。但我顯然想要跳過SQL,除非有必要。如何使Rails中的has_many關係失效

因此,例如:

class Student 
    has_many courses # may have a :condition clause or some such 

    def some_method 
    # For some reason, we want to change all courses in here, not 
    # just a single row. 
    ActiveRecord::Base.connection.execute("UPDATE courses SET location = #{new_location}") 
    # Not sure if we'll later do anything with self.courses, so I need to invalidate 
    # that relationship. Could do self.courses.reload right here, but I don't want to 
    # do the SQL if it isn't necessary; the cache only lasts until the end of the 
    # current page request. 
    end 
end 

我可能失去了一些東西相當明顯。一些假設的self.courses.invalidate方法。

回答

5

不在他們的公共API中,但是您可以在AssociationCollection class上嘗試重置方法。

看日誌:

s = Student.first 
s.courses  # Hits db 
s.courses  # Hits cache 
s.courses.reset # No db 
s.courses  # Hits db 
+0

這正是我所需要的。謝謝! – ChrisInEdmonton 2010-08-17 15:10:12

+1

公共API,來自has_many文檔:collection(force_reload = false) – 2013-10-20 16:28:17

1

在140個字符中我不能說的擴展...您可以避免使用一些附加到關聯的Rails便捷方法來使關係無效。比方說,例如,我有一個用戶和項目模式:

class Project < ActiveRecord::Base 
    # Backing table has :id, :user_id, :name, and :description columns 
end 

class User < ActiveRecord::Base 
    has_many :projects 
end 

user = User.first # Assuming you have some users already 

# Creates a new project named "Some Project" with description "Some Description" 
# and sets the project's user_id to user.id. Also handles in-memory user.projects 
# updating. 
user.projects.create(:name => "Some Project, :description => "Some Description") 
+0

絕對是真實的,但如果我更新,沒有創造,數據,我最終通過在關聯的元素進行迭代,並呼籲節省他們每個人。比方說,有50個關聯的行,那就是50個SQL語句,這正是我想要擺脫的。儘管如此,您的示例仍然是更常見的情況,儘管它不能解決我的問題+1。 – ChrisInEdmonton 2010-08-16 22:37:23

0

你應該有update_attribute方法哪個更新通過SQL,但有改變本地屬性的優勢,一看版本。

+0

但是,這不僅僅是更新單行上的一列或多列?這不會幫助我。也許我錯誤地閱讀了一些東西,但是有一些方法可以在所有行中調用update_attribute。 – ChrisInEdmonton 2010-08-17 01:35:43