2012-12-04 7 views
1

두 모델이 있는데 하나는 다른 모델에 속해 있고 제대로 저장하지 못하는 것 같습니다. 문제는 모델에서 build 메서드를 사용할 때 메모리에 서로 할당하지 않기 때문에 부모에게 .save을 호출하려고하면 부모의 ID가없는 것입니다. 설정하고 실패합니다. ,레일 : has_one belongs_to 관계를 제대로 구축하지 않음

@execution = Execution.find(1) 
@em = @execution.execution_macros.build(:macro_type_id => 1, :macro_key_id => 1) 
@ae = @em.build_advertisement_execution(:advertisement_id => 1, :advertisement_version_id => 1) 
if @em.save 
    "do something" 
else 
    "throw an error" 
end 

내성 굴림 실패 할 것이다 : 나는 다음과 같은 코드를하려고하면

# id      int(11) 
# advertisement_id   int(11) 
# execution_macro_id  int(11) 
# advertisement_version_id int(11) 
# created_at    datetime 
# updated_at    datetime 
# deleted_at    datetime 

class AdvertisementExecution < ActiveRecord::Base 
    belongs_to :advertisement 
    belongs_to :advertisement_version 
    belongs_to :execution_macro 

    attr_accessible :advertisement_id, :advertisement_version_id, :execution_macro_id 

    validates :execution_macro, :presence => true 
    validates :advertisement, :presence => true 
    validates :advertisement_version, :presence => true 
end 

그래서, 다음은

# id    int(11) 
# execution_id int(11) 
# macro_type_id int(11) 
# macro_key_id int(11) 
# created_at  datetime 
# updated_at  datetime 

class ExecutionMacro < ActiveRecord::Base 
    belongs_to :execution 
    belongs_to :macro_type 
    belongs_to :macro_key 
    has_one :advertisement_execution, :dependent => :destroy 
    accepts_nested_attributes_for :advertisement_execution 

    attr_accessible :macro_key_id, :macro_type_id, :advertisement_execution_attributes 

    validates :execution, :presence => true 
    validates :macro_type, :presence => true 
    validates :macro_key, :presence => true 
end 

아이입니다 :

다음은 상위 모델입니다 "광고 실행 : 실행 매크로를 비워 둘 수 없습니다."

이렇게 힘들지는 않습니다. 내가 뭘 놓치고 있니?

+0

개체가 아닌 ID의 유효성을 검사 해보십시오. 이렇게 : validates : execution_macro_id, : presence => true' – MrYoshiji

+0

주사위가 없습니다. 아무것도 바뀌지 않았습니다./ –

+0

유효성 검사를 제거하면 올바르게 저장됩니까? – agmin

답변

1

당신이 build_advertisement_execution을 호출하는 동안 @em이 데이터베이스에 저장되지 않는다는 것이 트릭입니다. 이 경우 @ em.id와 @ ae.id는 nil과 동일하므로 (지속되지 않기 때문에) @ ae.execution_macro_id와 @ em.advertisement_execution_id도 nil로 설정됩니다.내 제안은 advertisement_execution (.save (validate : false) 참조)을 만들기 전에 검증 논리를 다시 생각하거나 유효성 검사없이 execution_macros를 저장하는 것입니다.

관련 문제