Aaquib Khan
Aaquib Khan

Reputation: 83

Update nested models in rails api

I'm wanting to build a Rails API that creates nested records in the database.

I'm wanting to post data to the database for nested or say associated model with a has_ many association [see code below].

Is this the correct approach? Or is there any alternate approach for the update action? I want to record the users Address which will be in array of hashes in json format.

I have two models User and Address. Association is User has_many Addresses.

My update action:

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

    if @user.update(first_name: params[:first_name],email: params[:email],phone: params[:phone],password: Time.now.to_i, gstin: params[:gstin],addresses)
      @user.addresses.each do |a|

        a.update_attributes(first_name: params['first_name'],last_name: params['last_name'],city: params['city'],state: params['state'],phone: params['phone'],zip: params['zip'],address: params['address'])
      end  
      render json: @user, status: 200
    else
      render json: { errors: @user.errors }, status: 422
    end
  end

Upvotes: 3

Views: 762

Answers (2)

Aaquib Khan
Aaquib Khan

Reputation: 83

I figured it out and writing the answer for the people who get stuck.

As I was not using strong params and I needed only the address in json format, I parsed the address json like this:

def update
    @user = User.find(params[:id])
    if @user.update(first_name: params[:first_name],email: params[:email],phone: params[:phone], gstin: params[:gstin])
      updated_addreses = JSON.parse(params[:addresses])
        updated_addreses.each do |add|
          @user.addresses.update(first_name: add['first_name'],city: add['city'],state: add['state'],phone: add['phone'],zip: add['zip'],address: add['address'])
        end  
      render json: {user_id: @user.id.to_s}, status: 200
    else
      render json: { errors: @user.errors }, status: 422
    end
  end

Upvotes: 1

Anand
Anand

Reputation: 6531

thats not correct way to do you should use accepts_nested_attributes_for

Class User 
  has_many :addresses
  accepts_nested_attributes_for :addresses
end

for more details and example follow this

Upvotes: 1

Related Questions