简体   繁体   中英

Rails 4 - save / update nested record

I have user and user has one address. I need to create a form which is like edit profile page. Which will save few user's fields and save user's address. But everytime while I submit form, user's data is correctly being saved in DB, but for address, new record is being created every time with correct user_id value and other field value is null.

Query: How to save address in database?

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

<%= 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' %>

controller

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

Your country_id select field will return a string, while your Address model probably expects an integer. This might prevent the record from being saved correctly?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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