2011-11-02 3 views
2

을 실행되지 않습니다 잘못된. User#invite_user!가 왜액티브 콜백은 다음 사양을 감안할 때

# Check the before_validation callback options: 
participation.user # nil 
participation.valid? # true 
participation.user # User{id: nil} 

# Check the before_create callback options: 
participation.user_exists? # false 
participation.mark_for_invitation # true 

# Check the after_create callback options: 
participation.marked_for_invitation? # true 

# After all this I expect the "invite_user!" to be called: 
participation.stub(:invite_user!) { puts "Doesn't get called :(" } 
participation.save! # => true, Nothing is printed, which is consistent with the spec 
participation.user_id # => 11, so the user has been saved 

당신은 문제를 발견 할 수를 호출되지 않습니다 다음은 실패 사양에서 "콘솔"출력은?

+1

rspec 및 레일 버전을 제공해주십시오. 해당 코드에는 명백한 문제가 없습니다. – Sigurd

+1

after_create 콜백 대신 after_save를 사용하면 작동합니까? – John

+0

실제로 그렇습니다. –

답변

6

belongs_to 연결의 기본값은 :autosave => true입니다. 따라서 사용자 레코드는 Partecipation이 저장 될 때 지속되고 활성 레코드를 구현하는 방법은 단순히 사용자를 저장하는 before_save 콜백을 정의하는 것입니다.

before_save 콜백 [1] 후에 mark_for_invitation 콜백이 호출되기 때문에 사용자 연결이 저장된 후에 mark_for_invitation 콜백이 "호출"되므로 실제로 그 시점에서 :user_exists? 메서드가 항상 true이므로 실제로 실행되지 않습니다. http://pivotallabs.com/users/danny/blog/articles/1767-activerecord-callbacks-autosave-before-this-and-that-etc-

:

before_save :mark_for_invitation, :on=>:create, :unless => :user_exists? 

과 belongs_to 여기

전에 넣어이 문제를 설명하는 기사입니다 :

솔루션은에

before_create :mark_for_invitation, :unless => :user_exists?

을 변경하는 것입니다

[1] 참조 : http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

+0

질문에 대한 설명과 관심을 가져 주셔서 감사합니다. –

관련 문제