0
votes

I am new to rails and building an app to fetch json data from an external website and save it in the database. The json has the following fields under User:

{ "id": , "name": " ", "username": " ", "email": " ", "address": { "street": " ", "suite": " ", "city": " ", "zipcode": " ", } "phone": " ", "website": " " },

I know how to create a User model with name, username, and email. But how do I add address that has multiple sub-attributes. I did not see "array" as an option to choose from for creating model. Thank you in advance.

2

2 Answers

1
votes

You can do this by associating addresses to a user.

First you should create a new model called user_address for example, with the attributes you desire:

rails g model user_address address:string number:integer user_id:integer

On your user_address.rb file:

belongs_to :user

Then, in your user.rb file you should add

has_many :user_addresses

Once you do this you'll be able to access all the user's addresses by doing the following query:

user.user_addresses

this will give you an 'ActiveRecord::Associations::CollectionProxy' object, where you will be able to iterate:

user.user_addresses.each do |address_instance|
  puts address_instance.address+"#{ address_instance.number}"
end

To manage this in a form, you could follow this guide: https://github.com/nathanvda/cocoon/wiki/A-guide-to-doing-nested-model-forms

0
votes

I think you can try this:

class NameOfYourMigration < ActiveRecord::Migration

  def change
    add_column :your_models, :address, :text
  end

end

class YourModel < ActiveRecord::Base 
 serialize :address, Hash  # if your variable is a Hash
 serialize :address, Array # or for an Array
end