I have a Statuses table which contains only an id and name field (Active, Inactive, Pending, etc). I then have tables such as Users, Achievements, Badges for which each of these contain a status_id foreign key. Do the associations in my models look correct?
class Status < ActiveRecord::Base
has_many :achievements
has_many :badges
has_many :users
end
class User < ActiveRecord::Base
belongs_to :status
end
class Badge < ActiveRecord::Base
belongs_to :status
end
class Achievement < ActiveRecord::Base
belongs_to :status
end
I am struggling with how to properly read the difference between has_one and has_many in the case of a lookup table. I know that a user has one company and has one profile and a company has many users but this seems backwards to me.
The simplest association setup would be:
That exactly describes what you have posted. Your solution would work, but it is overkill for what you’ve described. All the association I posted above would do is add one method to the user model, i.e.
If on the other hand you wanted simple semantics for showing all the users with a particular status, THEN you’d add
so now you could do:
Note that in BOTH cases, all that is needed is for the users model to have an attribute ‘status_id’
Belongs_to is better suited when there is an implicit hierarchy , i,e,