1

I'm trying to figure out what is the proper way to setup my model and database if I have a list under itineraries...

Database Table

`users`
id

`itinerary`
id
user_id
items

Model

class User < ActiveRecord::Base
  has_many :itineraries
end

class Itinerary < ActiveRecord::Base
  belongs_to :user
end

This is the basics, but what if I want to have users to input multiple items within their itinerary? Should I have a separate model and table for that? so under itinerary Database Table instead of items, it should be item_id?

`itinerary`
id
user_id
item_id    # the change here

And have a separate items table:

Database Table

items
id
itinerary_id    # relationship id
name

Model

class Item < ActiveRecord::Base
  belongs_to :user
  belongs_to :itinerary
end

class Itinerary < ActiveRecord::Base
  belongs_to :user
  has_man :items
end

Or if this isn't the correct way, how do you display a list of items within the itinerary database table?

Thanks!

hellomello
  • 8,219
  • 39
  • 151
  • 297
  • you are doing correct. each item has itinerary_id and user_id in it. this way it is assosiated to both itinerary and user. you can fetch using: user.items or itinerary.items. or similarly user.itineraries.collect(&:items).flatten.compact. this way you will fetch all items against all itineraries for that user. – Athar Jul 14 '15 at 15:38
  • Can a single item belong to multiple itineraries? – David Aldridge Jul 14 '15 at 15:45
  • @Athar so to understand, I should have a separate `items` table? I guess this makes more sense because if you're having multiple items, and if the database needs to grow, you'd need to create a different table for this... – hellomello Jul 14 '15 at 18:59
  • Yes you should. This is how you will have itinerary_I'd and user_I'd in it – Athar Jul 14 '15 at 21:53
  • If you are allowing to create items againsy itinerary by all users. Ie different users can create items for all itineraries then I would suggest to add user_id in items table.Else if only the user who create itinerary can only create item for that itinerary then surely you don't need user_I'd in item table – Athar Jul 14 '15 at 22:24

2 Answers2

1

Adding to the answer of Puce, for the has_many relationship, you need not have a column item_id under itinerary table.

It is enough if you have the itinerary_id in items table alone.

0

If you relate the item with the itinerary, you don't need to relate it to user, because you could call it like:

my_items = user.itineraries.where(name: 'foo').items

I don't see why you would need to relate user and item directly, depends on your business logic, what you need, etc.

Puce
  • 1,003
  • 14
  • 28