Jump to content

The ultimate community for Ruby on Rails developers.


Photo

Noob association question

associations

  • Please log in to reply
1 reply to this topic

#1 panzhuli

panzhuli

    Passenger

  • Members
  • 3 posts

Posted 20 January 2014 - 12:55 AM

I'm pretty new at Rails and am setting up a new application that is user based. My data model is a bit complicated so I'm trying to figure out how much I have to associate with each user. Here's a generic rundown: a user has an inventory of items. Each item has the following:

 

Title

Date

Quantity

Price

Status [for sale, sold, not for sale]

Location

 

-BUT-

 

It is possible that if the user has many copies/versions of an item so that each location may have N number, with a price, some number are sold, unsold, etc.

 

I've thought about having a model setup like this:

 

User

has_many :items

has_many :locations

has_many :itemSets # <--- DO I NEED THIS???

 

Item

belongs_to :user

has_many :item_sets

Title

Date

Quantity

 

ItemSet

belongs_to :item

has_one :location

belongs_to :user # <--- ???

Quantity

Price

Status [sold, for sale, not for sale]

 

Is this the right association concept? And do I have to associate ItemSets to users? I'll never be showing them outside of their association with an item... Thanks and I hope this makes sense!!



#2 erowlin

erowlin

    Passenger

  • Members
  • 9 posts

Posted 18 February 2014 - 04:44 AM

Almost right. 

 

Yes, you need has_many and belongs. 

 

There is 1 problem I think, it's that the user won't access directly the Items, the correct route is user -> itemset -> item, right ? 

 

so 

 

item model : 

belongs_to :user

belongs_to :item_set

 

itemset model : 

has_many :items

belongs_to :user

 

user model : 

has_many :itemsets

has_many :items, through: :itemsets

 

The user don't access directly the items, but he still has items. So the user will access items through the itemset model. 







Also tagged with one or more of these keywords: associations

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users