1

, 나는 몇 가지 clients 있고, 그들은 여러 elements (협회 has_many_through를 통해)이 모든 Clientelements, I BusinessType을 선택하면 모든 것이 자동으로 추가됩니다 (business_type : Clientattr_readonly). BusinessType HABTM elements.얻기 이전 HABTM 값 내 응용 프로그램에서

가정하자 : 여기

기본 BusinessType로 만든 후, 클라이언트가 자신의 요소를 업데이트하고 제거하거나 원하는대로 (대부분 추가) 추가 할 수 있습니다, 캐치, 그래서 난 할 노력하고있어 다음이다 하나의 business_type[1,2,3]이고 하나는 client이고 다음 요소는 client = [4,5,6]에 수동으로 추가되어 결국 [1,2,3,4,5,6]이됩니다. 모든 항목이 정상입니다.

그러나이 후에 business_type은 업데이트되고 요소 2이 제거되어 결국 [1,3]이됩니다. 여기 거래가 있는데 2을 제거하여 클라이언트를 업데이트하려고하지만 으로 끝나기 위해 business_type에 해당하지 않는 [4,5,6]이 아니라면 clients' 요소를 업데이트하기 위해 after_update 콜백을 사용하고 있습니다. _was 방법은

. 이전 business_type's 요소를 얻기 위해 (HABTM 관계 작동하지 않습니다 내가 먼저 client.elements = client.elements - business_type.elements에 DB [1,2,3,4,5,6] - [1,2,3] = [4,5,6]에 일시적으로 저장하는 before_update 콜백을 사용하여 시도했다 및 after_update에 [4,5,6] + [1,3] = [1,3,4,5,6]를 얻을 수 client.elements = client.elements + business_type.elements을 그러나 이것은 이미 새로운 값인 [1,3]입니다. 어떻게 이전을 얻을 수 있습니까? 또는 after_update의3210 값은?

미리 도움 주셔서 감사합니다.

답변

1

나는 앱에서 비슷한 문제를 겪었고 컨트롤러에서 update_attributes를 수행하기 전에 값을 저장하는 것이 유일한 해결책이었다.

예제 코드 : 그것은 좋지 않은

class ProductsController < ApplicationController 
    ... 

    def update 
    @product.remember_prev_values(@product.category_ids) 
    if @product.update_attributes(params[:product]) 
     flash[:notice] = "Product was successfully updated." 
     redirect_to(product_path(@product)) 
    else 
     render :action => "edit" 
    end 
    end 

    ... 

end 

하지만 그 다음입니다 :

모델

class Product < ActiveRecord::Base 
    has_and_belongs_to_many :categories, :join_table => "categories_products" 

    def remember_prev_values(values) 
    @prev_values = values 
    end 

    def before_update_do_something 
    puts @prev_values - self.category_ids # Any categories removed? 
    puts self.category_ids - @prev_values # Any categories added? 
    end 
end 

class Category < ActiveRecord::Base 
    has_and_belongs_to_many :products, :join_table => "categories_products" 
end 

제품 컨트롤러의 업데이트 방법에서 나는 다음을 수행 habtm 삽입/제거가 실행되기 전에 "catch"할 수 있습니다.

콜백에서 할 수 있다고 생각하지만 ActiveRecord에 "해킹"해야 할 수도 있습니다.

ActiveRecord 내부를 조사하는 데 많은 시간을 할애하지 않았습니다. 이는 이것이 작동하는 간단한 구현이기 때문입니다.

0

이전 값을 저장하려면 after_initialize 콜백을 사용해야합니다.

after_initialize do @previous_elements = elements.map{|x| x} end 

지도 함수 호출로 assosiations 사본을 만듭니다.