2012-03-23 151 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。不在你的客戶端。所以當你從客戶端創建一個聯繫人時,在你的客戶端中只有一個client_id被定義在你的聯繫人中沒有contact_id。

所以刪除行:

validates :contact_id, presence: true 

# Fields 
field :contact_id 
在您的客戶端模型