Rails 4 - 保存/更新嵌套记录

时间:2015-10-13 10:06:51

标签: ruby-on-rails

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

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

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

1 个答案:

答案 0 :(得分:0)

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