Reputation: 3500
How do I Access data through this Many_to_Many relation?
Here are my database creations:
The "Useres":
class CreateSubgroups < ActiveRecord::Migration
def change
create_table :subgroups do |t|
t.string :name
t.belongs_to :group
t.timestamps
end
end
end
The relationship:
class CreateRtimespans < ActiveRecord::Migration
def change
create_table :rtimespans do |t|
t.belongs_to :subgroup_id
t.belongs_to :timespan_id
end
end
end
The Used:
class CreateTimespans < ActiveRecord::Migration
def change
create_table :timespans do |t|
t.string :name
t.text :descrition
t.integer :start_h
t.integer :start_m
t.integer :end_h
t.integer :end_m
end
end
end
How do I for example access the names of all timespans, that belong to one subgroup? And vis versa, how can I show, which subgroups use a specific timespan?
Upvotes: 0
Views: 75
Reputation: 1439
As your code suggest you have got two models as
Subgroup
and
TImespan
since there is a many to many relation between them we can use them as
# all timespans related to a subgroup
subgroup.timespans # where variable subgroup is a Subgroup object
and
# all subgroups related to a timespan
timespan.subgroups # where variable timespan is a Timespan object
Upvotes: 1
Reputation: 4927
First question
You can do whatever find call as long as you get a instance. I get a instance by calling .first on the model.
Subgroup.first.timespans.each do |timespan|
puts timespan.name
end
Vis versa
Timespan.first.subgroups.each do |subgroup|
puts subgroup.name
end
Upvotes: 1