2012-03-23 5 views
0

클라이언트와 has_one 관계가있는 연락처를 만들려고합니다. 중첩 된 특성을 사용하여이 작업을 수행하고 있습니다. "새로운"보기/컨트롤러 내에 연락처를 올바르게 구축하고 있습니다. 연락처를 저장하려고하면 연락처가 있어야한다는 메시지가 나타납니다. 그래서 어떤 이유로 연락처를 생성하지 않습니다.몽고 이드 has_one 관계에 중첩 된 특성

ERROR :

Validation failed - Contact can't be blank. 

에 Params :

{ 
    "utf8"=>"✓", 
    "authenticity_token"=>"ep6es356WY5dja7D7C5Kj8Qc0Yvuh3IN2Z1iGG08J7c=", 
    "client"=>{ 
    "contact_attributes"=>{ 
     "first_name"=>"Scott", 
     "last_name"=>"Baute" 
    }, 
    "commit"=>"Create Client" 
} 

모델 :

class Client 
    include Mongoid::Document 
    include Mongoid::Timestamps 

    attr_accessible :role, :contact_id, :contact_attributes 

    # Relationships 
    belongs_to :firm, validate: true 
    has_one :contact, validate: true, autosave: true 

    # Matters is custom relationship 
    has_many :client_roles 

    # Nested Attr 
    accepts_nested_attributes_for :contact 

    validates :contact_id, presence: true 

    # Fields 
    field :contact_id 
    field :test 
end 

class Contact 
    include Mongoid::Document 
    include Mongoid::Timestamps 
    include Mongoid::MultiParameterAttributes 

    #Relationships 
    belongs_to :client 

    field :first_name 
    field :last_name 

end 

컨트롤러 :

# GET /clients/new 
# GET /clients/new.json 
def new 
    @client = current_firm.clients.new 

    respond_to do |format| 
    format.html # new.html.erb 
    format.json { render json: @client } 
    end 
end 

# POST /clients 
# POST /clients.json 
def create 
    @client = current_firm.clients.new(params[:client]) 

    respond_to do |format| 
    if @client.save! 
     format.html { redirect_to client_path(@client.contact.id), notice: 'Client was successfully created.' } 
     format.json { render json: @client, status: :created, location: @client } 
    else 
     format.html { render action: "new" } 
     format.json { render json: @client.errors, status: :unprocessable_entity } 
    end 
    end 
end 

보기 :

- @client.build_contact unless @client_contact 
= semantic_form_for @client, html: { class: "form-horizontal"} do |f| 
    .control-group 
    = render "contact_fields", f: builder  
    .form-actions 
    = f.submit class: "btn btn-primary" 

답변

0

나는 당신이 당신의 클라이언트 모델에서 contact_id하는 참조를 삭제할 필요가 있다고 생각합니다. has_one 연관은 귀하의 연락처에서 foreign_key를 수행합니다. 당신의 고객이 아니에요. 따라서 클라이언트에서 연락처를 만들면 클라이언트의 contact_id에 client_id 만 정의됩니다.

그래서 삭제 라인 : 당신의 클라이언트 모델에서

validates :contact_id, presence: true 

# Fields 
field :contact_id 

.