Stan
Stan

Reputation: 141

Rails - Linking two models with has_many relationship

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

Answers (2)

Richard Peck
Richard Peck

Reputation: 76774

What you've got there is a standard has_many/belongs_to relationship:

enter image description here

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:

  1. If you have an ActiveRecord association in your system, it has to be bi-way -- IE if you have has_many :classes, it has to be matched with belongs_to :class (unless you do lots of configuration
  2. When declaring belongs_to associations, you need to keep the association singular. You write it as plural
  3. When declaring associations, you can only have one association per name. Your use of belongs_to :users and has_many :users simply would not be recognized.
  4. All associations are basically covers for particular SQL associations. You'd do well to read up on relational databases, and how their foreign keys allow them to interact
  5. The terms "class, klass" are generally reserved in most languages. Don't use them

has_and_belongs_to_many

Now, if you wanted to make many-to-many relationship, you'd use has_and_belongs_to_many:

enter image description here

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

Sanjay Singh
Sanjay Singh

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

Related Questions