2012-03-23 5 views
0

クライアントとの関係がhas_oneである連絡先を作成しようとしています。私はネストされた属性でこれをやっています。私は適切に "新しい"ビュー/コントローラ内の連絡先を構築しています。私が連絡先を保存するために行くと、連絡先が存在しなければならないと私に伝えています。それで何らかの理由で連絡先が作成されていません。Mongoidのネストされた属性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を行います。あなたのクライアントではありません。したがって、クライアントから連絡先を作成するときは、クライアントの連絡先no contact_idにclient_idだけが定義されています。

ので、削除行:あなたのクライアントモデルにおける

validates :contact_id, presence: true 

# Fields 
field :contact_id