0

I have some problems setting up my desired relationship in my application. Some help and hints would be appreciated!

I have the following models:

  • User (id, username)
  • Company (id, name)
  • Campaign (id, name, company_id)
  • Relationship (user_id, company_id)

The relationship is supposed to connect the user to many companies. Company has_many campaigns.

I want to to connect all the campaigns related to the companies that the specific user follows.

Users > (Relationships) > Companies > Campaigns

I'd better not post some code since it's just a mess and not at all doing what I want.

I've also really tried to follow railstutorial.org, http://ruby.railstutorial.org/chapters/following-users#top and change it the way I want with no success.

I need your help. :)

1 Answer 1

1

Should be pretty straightforward! This is obviously pseudocode, but here you go:

User has_many :relationships has_many :companies, :through => :relationships has_many :campaigns, :through => :companies Relationship belongs_to :user belongs_to :company Company has_many :relationships has_many :users, :through => :relationships has_many :campaigns Campaign belongs_to :company 
Sign up to request clarification or add additional context in comments.

3 Comments

That's great, thanks! My code wasn't so bad, most like yours but you had some relation that made it work. It is set up now and I can for instance do User.first.companies and get all of the companies that the first user are following. But what I wanted was to be able to iterate through campaigns (that belongs to the companies I follow). And I don't see how I should do that relation, it's kind of a through => through?
You can't use has_many through unless the join table has a primary key (id).
has_many :campaigns, :through => :companies in the User model seems to make it work?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.