Kintarō
Kintarō

Reputation: 3177

Ruby on Rails: What is the best way to update embedded document?

I am using Mongoid for my Rails app. Currently I have these two models:

class User
  include Mongoid::Document

  field :name, type: String

  embeds_many :addresses
end

class Address
  include Mongoid::Document

  field :street, type: String

  embedded_in :user
end

My app will use REST API to create/delete/update the user along with the addresses.

However, when user want to add a new address or remove a new address from the existing user account. I need to compare the current address list one by one to see if it is a new address or old address in order to do the update operation; This method is very tedious.

Another choice is to have a set of REST API for Address it self. However, I don't want to use REST API for the Address model because I can foresee there will be a lot of embedded document coming base on requirement.

Just wonder what is the best choice to update an embedded document generally?

Thanks

Upvotes: 0

Views: 185

Answers (2)

a14m
a14m

Reputation: 8055

Whether you will have a separate resource for Address or add it to the update user, make sure that it'll work with your front-end/api consumers.

For example if you are using ember js (specifically ember-data) you have to make the address operations in the user update cause ember-data doesn't support having the embedded resources as a separate stand alone models in the front end (AFAIK)...

so although I prefer making the address as a separate resource and treat it as if it's not embedded, you will have to make sure that what ever design/solution you choose will work in the full stack.

Upvotes: 1

nort
nort

Reputation: 1615

Generally best to understand that if you have tedious requirements sometimes it takes tedious implementations. That being said, I would have an endpoint for addresses and treat them as if they are not embedded, search for them on the user (by id or other identifier), remove, update or create them as you would if it was not embedded.

Upvotes: 0

Related Questions