Artyom Gunkin
Artyom Gunkin

Reputation: 73

Rails has_many associations at both sides

I have users. Every user can create journey. When user create journey, other users can join to jorney. How to create associations right?

In user_model:
has_many :journeys
In journey_model:
belong_to :user
Can I add to journey_model: has_many :users?

Upvotes: 1

Views: 770

Answers (1)

Richard Peck
Richard Peck

Reputation: 76774

#app/models/user.rb
class User < ActiveRecord::Base
   has_many :created_journeys, class_name: "Journey", foreign_key: :user_id
   has_and_belongs_to_many :journeys
end

#Need a table journeys_users - journey_id | user_id

#app/models/journey.rb
class Journey < ActiveRecord::Base
   belongs_to :owner, class_name: "User", foreign_key: :user_id
   has_and_belongs_to_many :users
end

This will allow you to call the following:

@user = User.find params[:user_id]
@journey = @user.journeys.find params[:id]

@journey << current_user

Many-to-Many

The crux of your issue is that you're looking for a many-to-many association.

This comes in two flavours:

Both of these work to deliver a similar result, just in different ways:

enter image description here

I can explain more if required.

Upvotes: 3

Related Questions