Reputation: 141
I've already spent weeks on this. I have two models: User and Classes The User model can have many Classes and Classes can have many Users
Here's my Class Model:
class Class < ActiveRecord::Base
has_many :users
belongs_to :users
end
And the User Model
class User < ActiveRecord::Base
has_many :discipleship_classes
end
I can't figure out how to configure the #show method in the User controller to show multiple classes and vice-versa -> show multiple users when viewing Classes.
Any help would be appreciated.
Upvotes: 1
Views: 591
Reputation: 76774
What you've got there is a standard has_many/belongs_to
relationship:
Thus, your models should be constructed as so:
class DisclipleClass < ActiveRecord::Base
#columns id | user_id | etc | etc | created_at | updated_at
belongs_to :user
end
class User < ActiveRecord::Base
has_many :disciple_classes
end
Several important notes:
has_many :classes
, it has to be matched with belongs_to :class
(unless you do lots of configurationbelongs_to
associations, you need to keep the association singular. You write it as pluralbelongs_to :users
and has_many :users
simply would not be recognized.has_and_belongs_to_many
Now, if you wanted to make many-to-many
relationship, you'd use has_and_belongs_to_many
:
This will give you the ability to use the following:
#app/models/user.rb
class User < ActiveRecord::Base
has_and_belongs_to_many :disciple_classes
end
#app/models/disciple_class.rb
class DiscipleClass < ActiveRecord::Base
has_and_belongs_to_many :users
end
This will allow you to create a join table as follows:
#disciples_classes_users
disciple_class_id | user_id
This will allow you to call:
@user.disciple_classes
@disciple_class.users
Upvotes: 2
Reputation: 367
In show
view for @user
,
<% @user.discipleship_classes.each do |d_class|%>
<%= d_class.class.name%>
<%= d_class.some_intrinsic_detail_of_discipleship%>
<% end %>
Upvotes: -1