Bounce
Bounce

Reputation: 2095

has_and_belongs_to_many - getting data from join table

My rails app uses three tables: A, B, C. A table is related to table C through table B. Relation is many-to-many. Also table B contains some extra fields like rel_date, etc. Relation between tables works fine, but I do not know how to get B table extra fields data.Because if I make A.Cs, I only get C table elements that are related to table A. Don't know how to get all fields that are in table B?

Any ideas?

Upvotes: 0

Views: 507

Answers (2)

Douglas F Shearer
Douglas F Shearer

Reputation: 26488

You want to use has_many through.

class ModelA < ActiveRecord::Base
  has_many :model_b
  has_many :model_c, through: :model_b
end

class ModelB < ActiveRecord::Base
  has_many :model_a
  has_many :model_b
end

class ModelC < ActiveRecord::Base
  has_many :model_b
  has_many :model_a, through: :model_b
end

Now you can access C from A and vice-versa, as you did before, but also access B from both too.

Upvotes: 2

DaveMongoose
DaveMongoose

Reputation: 905

Rails has a has_many ... through association type that does what you're after:

class Restaurant < ActiveRecord::Base
  has_many :restaurant_dishes
  has_many :dishes, through: restaurant_dishes
end

class RestaurantDish < ActiveRecord::Base
 belongs_to :restaurant
 belongs_to :dish

 # Other attributes, e.g. price
end

class Dish < ActiveRecord::Base
  has_many :restaurant_dishes
  has_many :restaurants, through: restaurant_dishes
end

This allows you to do things like @restaurant.restaurant_dishes.where(dish: @dish) to access the middle table, but still use the shortcut @restaurant.dishes if you're not interested in the middle table.

See http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association for more info

Upvotes: 2

Related Questions