1
votes

I'm working on an event site where users have items in their inventory that can be listed in their profile. For this I am using:

has_many :items

in my user.rb.

A user would then be able to attend any number of events. For each event, they would have a unique items list, i.e., items to bring to the event. I'm trying to figure out the associations in order to make this work.

In item_list.rb:

belongs_to :event
belongs_to :user
has_many :items

In item.rb:

belongs_to :user
belongs_to :item_list

In event.rb

has_many :item_lists

But what's baffling me is making sure that each list is unique to each event and user. Additionally, would my migration for item_list include an array of items?

Any insight would be appreciated.

1
What you mean by would my migration for item_list include an array of items?Pavan
When I generate my database migration for item_list, would I need to include a column of arrays, i.e. to hold item_idsAaronM

1 Answers

0
votes

But what's baffling me is making sure that each list is unique to each event and user.

If I'm not wrong, you are looking for validates_uniqueness_of with scope option.

In your item_list.rb, add

validates_uniqueness_of :event_id, scope: :user_id

This will ensure you have an item_list with unique event_id and user_id. In other words, each item_list is unique to each event and user.

When I generate my database migration for item_list, would I need to include a column of arrays, i.e. to hold item_ids

No, with how your associations are setup Rails will expect you to have item_list_id in items table. So if you want fetch items for an item_list, you would do @item_list.items