user1084769
user1084769

Reputation: 49

Rails Associations for Lookup Table

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.

Upvotes: 3

Views: 4058

Answers (1)

RadBrad
RadBrad

Reputation: 7304

The simplest association setup would be:

class User < ActiveRecord::Base
  has_one :status
end

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.

@user = User.find(1)
@user.status

If on the other hand you wanted simple semantics for showing all the users with a particular status, THEN you'd add

class Status < ActiveRecord::Base
  has_many :users
end

so now you could do:

@status = Status.find_by_description('Active').first()

@status.users

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,

class Child << ActiveRecord::Base
   belongs_to :parent
end

Upvotes: 8

Related Questions