2015-10-13 132 views
0

我有用户和用户有一个地址。我需要创建一个表单,就像编辑个人资料页面一样。这将节省少量用户的字段并保存用户的地址。但是每次我提交表单时,用户的数据都正确地保存在数据库中,但是对于地址,每次使用正确的user_id值创建新记录,而其他字段值为空。Rails 4 - 保存/更新嵌套记录

查询:如何在数据库中保存地址?

class User < ActiveRecord::Base 
    has_one :address 
    accepts_nested_attributes_for :address 
end 

class Address < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :country 
    attr_accessor :city, :zip_code, :street_address, :state 
end 

形式

<%= form_for @user, url: {controller: :profiles, action: :update} do |f| %> 
<%= f.text_field :first_name, autofocus: true, :placeholder => 'First Name' %> 
<%= f.text_field :last_name, :placeholder => 'Last Name' %> 

<%= f.fields_for :address do |address_fields| %> 
    <%= address_fields.select :country_id, options_for_select(["Select One", "Cell", "Work", "Office", "Home", "Other"],:disabled => ["Select One"]) %> 
    <%= address_fields.select :state, options_for_select(["Select One", "Cell", "Work", "Office", "Home", "Other"],:disabled => ["Select One"]) %> 
    <%= address_fields.text_field :city, :placeholder => 'City' %> 
    <%= address_fields.text_area :street_address, :placeholder => 'Street Address' %> 
    <%= address_fields.text_field :zip_code, :placeholder => 'Zip Code' %> 
<% end %> 

<%= f.submit "Update", :class => 'btn btn-primary' %> 

控制器

class ProfilesController < ApplicationController 
    def edit 
     @user = current_user 
     @user.build_address if @user.address.nil? 
    end 

    def update 
     @user = current_user 
     respond_to do |format| 
     if @user.update(user_params) 
      format.html { redirect_to welcome_url, notice: 'Your Profile was successfully updated.' } 
      format.json { render :show, status: :ok, location: @user } 
     else 
      format.html { render :edit } 
      format.json { render json: @user.errors, status: :unprocessable_entity } 
     end 
    end 
end 

private 

    def set_user 
     @user = User.find(params[:id]) 
    end 

    def user_params 
     params.require(:user).permit(:first_name, :last_name, :email, :phone_number, :date_of_birth, address_attributes: [ :id, :city, :country_id, :zip_code, :street_address, :state]) 
    end 

end 

回答

0

country_id选择字段将返回一个字符串,而你的地址模型可能期望一个整数。这可能会阻止记录被正确保存?