2010-08-16 3 views
0

레일즈 앱에서 has_many 관계가있는 클래스가 있습니다. 효율성을 위해 데이터베이스의 많은 행을 한 번에 업데이트하기 위해 일부 직접 SQL을 수행하고 has_many 관계를 더 이상 유효하지 않게 표시하려고합니다. 나중에 코드가 has_many 관계에 액세스하면 데이터를 다시로드하려고합니다. 하지만 필연적으로 SQL을 건너 뛰고 싶습니다. 그래서 예를 들면레일에서 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

+1

has_many 문서의 공용 API : collection (force_reload = false) –

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

0

당신은 지역의 특성을 변경하는 장점을 가지고 SQL을 통해 업데이트 할 수 있지만 update_attribute 방법의 빌드를 살펴 있어야합니다.

+0

그러나이 작업은 단일 행의 하나 또는 여러 열을 업데이트하는 것이 아닙니까? 그게 날 도와주지 않을거야. 아마도 잘못 읽는 중입니다. 모든 행에서 update_attribute를 호출 할 수있는 방법이 있습니다. – ChrisInEdmonton

관련 문제