繁体   English   中英

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

[英]Rails 4 - save / update nested record

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM