2011-08-23 2 views

답변

8

컨트롤러에서 처리해야합니다. 먼저 모델에서 저장을 실행 한 다음 레코드 필드를 성공적으로 업데이트하십시오.

class MyController < ActionController::Base 
    def index 
    if record.save 
     record.update_attribute :updated_by, current_user.id 
    end 
    end 
end 

또 다른 대안은 (나는이 하나를 선호) 논리를 래핑 모델에서 사용자 지정 방법을 만드는 것입니다. 내가 touch 만하지 타임 스탬프가 아닌 사용자 ID를 말할 수있는 예를

class Record < ActiveRecord::Base 
    def save_by(user) 
    self.updated_by = user.id 
    self.save 
    end 
end 

class MyController < ActionController::Base 
    def index 
    ... 
    record.save_by(current_user) 
    end 
end 
+0

한 터치 방식에 대해 : – lucapette

+0

이유를 모델에 넣어위한은 (저장하기 때문에, DRY 때문이다)는 하나의 컨트롤러가 아닌 앱의 여러 위치에서 호출 할 수 있습니다. 차라리 한 번 해보고 내 자신을 반복하지 않아도되고 항상 이것을 기억하는 것에 대해 걱정할 필요가 없습니다. – pixelearth

+0

그런 다음 Model.save_from_user (user)와 같은 새 메서드를 만들고 레코드를 저장하고 터치를 수행하는 논리를 배치하십시오. 그런 다음 컨트롤러에서 단순히 current_user를 인수로 전달하는 메서드를 호출하십시오. –

1

위해 나는 지금까지, 시몬 Carletti의 조언에 따라이 monkeypatch을 구현했습니다. 이것에 문제가 있습니까? 이 장치는 장치 번호 current_user과 함께 작동하도록 설계되었습니다. 다음

class ActiveRecord::Base 
    def save_with_user(user) 
    self.updated_by_user = user unless user.blank? 
    save 
    end 

    def update_attributes_with_user(attributes, user) 
    self.updated_by_user = user unless user.blank? 
    update_attributes(attributes) 
    end 
end 

그리고 createupdate 방법과 같이 이러한 전화 :

@foo.save_with_user(current_user) 
@foo.update_attributes_with_user(params[:foo], current_user) 
관련 문제