0
votes

I'm new to Rails and have some doubts about the kind of relationship do I need to use. Here is the case.

I have two models Offer and User, a user could belong to to many offers and offers can have many user. Also the users create the offers.

I think I have to use a has_many :through ralationship. For example I've created another model "Applicant". Applicant belongs_to user and belongs_to offer. But how is the relationship from the user and offer model? For example:

User Model

 has_many :offer, :through => :applicant

Offer Model

 has_many :user, :through => :applicant

My doubt is because I already have this two relationship

User Model

has_many :offers, :dependent => :destroy

Offer Model

belongs_to :user

After solve this, I guest I have to save the record in the applicant model from the applicanst_controller, right?

Thanks in advance

1

1 Answers

3
votes

What you have described is a many-to-many relationship using a join table. You're actually pretty close but you just need to remove the has_many :offers, :dependent => :destroy from your user model and the blongs_to :user in your offer model. It should look something like this:

class User < ActiveRecord::Base
  has_many :offers, :through => :applicants
end

class Applicant < ActiveRecord::Base
  belongs_to :users
  belongs_to :offers
end


class Offer < ActiveRecord::Base
  has_many :users, :through => :applicants
end

You don't have to worry about the dependent destroy part as associations are automatically removed as the corresponding objects are removed. With a many to many association it doesn't really matter how you go about building the relationship. Either of the following will work:

@user.offers << @offer

@offers.users << @user

If you don't need to store any information specific to your applicant join table (e.g., time stamps, descriptions) you might instead want to look at a has_and_belongs_to_many relationship. Check out choosing between has_many_through and has_and_belongs_to_many for reference.

Edit

Heres the code for a HABTM relationship:

class User < ActiveRecord::Base
  has_and_belongs_to_many :offers
end


class Offer < ActiveRecord::Base
  has_and_belongs_to_many :users
end