Rails belongs_to through association - ruby-on-rails

I'm trying to add a new model to an existing model mesh. The existing one works perfectly but I can't get the new one to work properly and am wondering if the association is able to work the way I'm trying to make it work. Update: As I just got asked: belongs_to through was something I've read while gooling about the problem. If it doesn't exist, would has_one through be the correct way? I tried it as well but it also didn't work.
Here is the existing mesh:
class Course
has_many :users, through: :enrollments
has_many :enrollments
end
class User
has_many :courses, through: :enrollments
has_many :enrollments
end
class Enrollment
belongs_to :course
belongs_to :user
# has fields :user_id, :course_id
end
Now a user should be able to rate a course he's completed. (If he has, there is an enrollment with his id and a course id.) I thought it would be best to write it as follows:
class Course
has_many :users, through: :enrollments
has_many :enrollments
has_many :ratings, through: :enrollments
end
class User
has_many :courses, through: :enrollments
has_many :enrollments
has_many :ratings, through: :enrollments
end
class Enrollment
belongs_to :course
belongs_to :user
has_one :rating
# has fields :user_id, :course_id
end
class Rating
belongs_to :enrollment
belongs_to :course, through: :enrollment
belongs_to :user, through: :enrollment
end
When I try to create a Rating in the console, I get the following error:
User.first.ratings.create(text: "test", course_id: Course.first.id)
ArgumentError: Unknown key: through
Update
When I use has_one through insted, I get the following error:
ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection: Cannot modify association 'User#ratings' because the source reflection class 'Rating' is associated to 'Enrolment' via :has_one.
Is it possible to do it this way at all? Thanks!

class Course
has_many :users, through: :enrollments
has_many :enrollments
has_many :ratings, through: :enrollments
end
class User
has_many :courses, through: :enrollments
has_many :enrollments
has_many :ratings, through: :enrollments
end
class Enrollment
belongs_to :course
belongs_to :user
belongs_to :rating
# has fields :user_id, :course_id, rating_id
end
class Rating
has_one :enrollment
has_one :course, through: :enrollment
has_one :user, through: :enrollment
end
Note: Add foreignkey columns
And if you there is just one/two columns in ratings table merge them into enrollments like this.
class Course
has_many :users, through: :enrollments
has_many :enrollments
end
class User
has_many :courses, through: :enrollments
has_many :enrollments
end
class Enrollment
belongs_to :course
belongs_to :user
# has fields :user_id, :course_id, rating-columns...
end

Structure
Maybe you're complicating this too much
class Enrollment
belongs_to :course
belongs_to :user
end
This means you have a join model which stores unique records, referencing both course and user. Your ratings are on a per user and course basis?
Why don't you just include rating as an attribute of your enrolment model?:
#enrolments
id | user_id | course_id | rating | created_at | updated_at
If you give rating a numeric value (1 - 5), it will give you the ability to rate the different enrolments like this:
user = User.first
course = Course.first
user.enrolments.create(course: course, rating: 5)
--
Ratings
This is, of course, based on your current model structure.
If you want to include ratings for courses by users (not tied to enrolment), you may wish to use a join model called course_ratings or similar:
#app/models/user.rb
Class User < ActiveRecord::Base
has_many :enrolments
has_many :courses, through: :enrolments
has_many :ratings, through: :courses, class_name: "CourseRating"
end
#app/models/course.rb
Class Course < ActiveRecord::Base
has_many :enrolments
has_many :students, through: :enrolments, class_name: "User"
has_many :ratings, class_name: "CourseRating"
end
#app/models/course_rating.rb
Class CourseRating < ActiveRecord::Base
belongs_to :course
belongs_to :user
end
This will allow you to call:
user = User.first
user.courses.first.ratings

Related

Deleting the through association record when deassociating

In a Rails 6.1 app, I have a standard has_many through association
class Enrollment < ApplicationRecord
belongs_to :topic
belongs_to :job_description, optional: true
end
class Topic < ApplicationRecord
has_many :enrollments
has_many :job_descriptions, through: :enrollments
end
class JobDescription < ApplicationRecord
has_many :enrollments
has_many :topics, through: :enrollments
end
Now, when updating a topic (removing a job description)
#topic.job_descriptions = [...]
#topic.save
The topic_id in the enrollments having the job_description_id no longer associated with the topic is set to NULL.
Is there a way to delete the row instead?
try changing
has_many :job_descriptions, through: :enrollments
to
has_many :job_descriptions, through: :enrollments, dependent: :destroy

Rails Complex Model Association, Shared Document Between Users and Teams

I have a complex model association in mind, and was wondering how I could accomplish it. This is what i want to accomplish.
I have a User and a Document model
A User can create documents. He is now the document admin.
He can add other users to his document, and give them permissions such as Editor, Viewer, Admin
He can also make a team, a group of users, and add multiple teams to his document. Each user on a team that the User has added to his document will also have permissions. A user can belong to many teams.
I am a little bit confused about the associations I will have to setup. This is the code I have so far, which has not incorporated the team aspect:
class User < ApplicationRecord
has_many :participations
has_many :documents, through: :participations
end
class Document < ApplicationRecord
has_many :participations
has_many :users, through: :participations
end
class Participation < ApplicationRecord
belongs_to :user
belongs_to :document
enum role: [ :admin, :editor, :viewer ]
end
I would recommend introducing a Team and TeamMembership models in a similary way to existing models. Also change the belongs_to association on Participation from user to a polymorphic participant.
class Team < ApplicationRecord
has_many :team_memberships
has_many :users, through: :team_memberships
has_many :participations, as: :participant
end
class TeamMembership < ApplicationRecord
belongs_to :team
belongs_to :user
end
class User < ApplicationRecord
has_many :team_memberships
has_many :teams, through: :team_memberships
has_many :participations, as: :participant
end
class Participation < ApplicationRecord
belongs_to :participant, polymorphic: true
belongs_to :document
enum role: [ :admin, :editor, :viewer ]
end
class Document < ApplicationRecord
has_many :participations
# if desired create a users method to conveniently get a list of users with access to the document
def users
#users ||= participations.flat_map do |participation|
case participation.partipant
when User
[participation.participant]
when Team
participation.participant.users
end
end
end
end
I would only add has_many :through associations as you discover a benefit/need to having them. That will reduce complexity of maintaining them unless you have specific use case for them. In the case of User having a teams association, it's pretty obvious that you'll be likely to want to get the teams that the user is a part of and since there's no specific information in the TeamMembership object that you are likely to need in that determination, it's a good has_many :through to have.
EDIT: Added Document model.
Since you already have a participation model, you can use that as the join model between users and teams. Since a user can belong to multiple teams, and a document can have multiple teams, you can use a has_many through relationship between teams and documents. We'll call it the DocumentTeam model.
class User < ApplicationRecord
has_many :participations
has_many :documents, through: :participations
has_many :teams, through: :participations
end
class Participation < ApplicationRecord
belongs_to :document
belongs_to :user
belongs_to :team, optional: true
enum role: [ :admin, :editor, :viewer ]
end
class Team < ApplicationRecord
has_many :participations
has_many :users, through: :participations
has_many :document_teams
has_many :document, through: :document_teams
end
class Document < ApplicationRecord
has_many :participations
has_many :users, through: :participations
has_many :document_teams
has_many :teams, through: :document_teams
end
class DocumentTeam < ApplicationRecord
belongs_to :document
belongs_to :team
end

How to do associations with two user types and one model with has and belongs to many relationships in rails?

I've been trying to solve this problem for a while now. Looked here, but it is not exactly what I need.
I have three models: User, Group, GroupMembership. User can be a teacher and a student, so user has different Roles through UserRoles table. Groups can have multiple teachers. What I want is something like this:
Role.rb
has_and_belongs_to_many :users #this works fine
User.rb
has_and_belongs_to_many :roles # this works fine
has_many :group_memberships
has_many :groups, through: :group_memberships
has_many :teachers, through: :group_memberships
has_many :students, through: :group_memberships
Group.rb
has_many :students, through: :group_memberships
has_many :teachers, through: :group_memberships
GroupMembership.rb
belongs_to :student
belongs_to :teacher
belongs_to :group
User with roles works fine, there is no problem with the different roles for user. The problem is with group memberships. The above is just something that I want to work, but in some cases I need to supply source or class name and I am not sure what exactly to do. And what kind of migrations should I create?
I'll delete this if required; I'm pretty sure you'd benefit from using source: in your User and Group models:
#app/models/user.rb
class User < ActiveRecord::Base
has_and_belongs_to_many :roles # this works fine
has_many :group_memberships
has_many :groups, through: :group_memberships
has_many :teachers, through: :group_memberships, source: :teacher
has_many :students, through: :group_memberships, source: :student
end
#app/models/group_membership.rb
class GroupMembership < ActiveRecord::Base
belongs_to :student, class_name: "User"
belongs_to :teacher, class_name: "User"
belongs_to :group
end
#app/models/group.rb
class Group < ActiveRecord::Base
...
has_many :students, through: :group_memberships, source: :student
has_many :teachers, through: :group_memberships, source: :teacher
end
This is not tested & I don't have super experience with source so it could be wrong.
The modeling is a bit off - GroupMembership should be acting as a many to many join model. That means that each user and group needs a GroupMembership to tie them together.
Also you would alter the relation between users and roles to be a has_many through: so that you can have metadata in the join model.
class User
has_many :user_roles
has_many :roles, through: :user_roles
has_many :group_memberships
has_many :groups, through: :group_memberships
end
class Role
has_many :user_roles
has_many :users, through: :user_roles
end
class UserRole
belongs_to :user
belongs_to :role
end
class Group
has_many :group_memberships
has_many :users, through: :group_memberships
end
class GroupMembership
belongs_to :user
belongs_to :group
end
To query for group users with a specific role you could now use:
teachers = group.users.where(users: { roles: [Role.find_by(name: 'teacher')])
To make this a bit more convenient we can setup special relations with conditions:
class Group
has_many :group_memberships
has_many :users, through: :group_memberships
has_many :teachers, ->{ where(users: { roles: [Role.find_by(name: 'teacher')] }) } through: :group_memberships, source: :user
end
Note that we need to specify source as it tells AR that "teacher" is in fact group_memberships.user.

How to correctly write my relationship/associations in Rails?

I have 4 Models and i am not sure what is the correct way to write my relationships/associations.
class User < ActiveRecord::Base
has_many :boards
has_many :lists
has_many :cards
end
class Board < ActiveRecord::Base
belongs_to :user
has_many :lists
end
class List < ActiveRecord::Base
belongs_to :user
belongs_to :board
has_many :cards
end
class Card < ActiveRecord::Base
belongs_to :user
belongs_to :list
end
If you want to be more explicit about your relationships, feel free to do the following (preferred in most every case):
class User < ActiveRecord::Base
has_many :boards, inverse_of: :user, dependent: :destroy
has_many :lists, inverse_of: :user, dependent: :destroy
has_many :cards, inverse_of: user, dependent: :destroy
end
class Board < ActiveRecord::Base
belongs_to :user, inverse_of: :boards
has_many :lists, inverse_of: :board
end
class List < ActiveRecord::Base
belongs_to :user, inverse_of: :lists
belongs_to :board, inverse_of :lists
has_many :cards, inverse_of :list
end
class Card < ActiveRecord::Base
belongs_to :user, inverse_of: :cards
belongs_to :list, inverse_of :cards
end
Finally, make sure any of your models that are dependent on another (e.g. Board belongs_to User) have the appropriate foreign key in their table. So, for example, Board will need to have a user_id foreign key to correctly create the association.
You can create a migration for any of those entities if you haven't already like so:
rails generate migration AddUserRefToBoards user:references

Ruby on Rails - Association

I have to create relationship between student, courses and enrolment.
One student can enrol in only one course.
A course can be enrolled by many students.
How to acheive this ?
I was able to create has_many_through relationship like this
class
Student < User
has_many :enrollments
has_many :course , through: :enrollments
end
class Course < ActiveRecord::Base
has_many :enrollments
has_many :students, through: :enrollments, class_name: "User"
end
class Enrollment < ActiveRecord::Base
belongs_to :student, class_name: "User"
belongs_to :course
end
But this works only for has_many on both the sides of students and courses.
But I want only one student to enrol in one course like this
class Student < User
has_one :enrollment
has_one :course , through: :enrollment
end
But this does not work. When I do this
Student.first.enrollment.create(course: Course.last)
I get an error like this
NoMethodError: undefined method `enrollment' for #<Student:0x007f7ff8baf4a8>
Thanks to Marek Lipka for suggesting this solution.
Add validation in Enrollment
class Enrollment < ActiveRecord::Base
belongs_to :student, class_name: "User"
belongs_to :course
validates :student , uniqueness: true
end
And use has_many enrollments
class Student < User
has_many :enrollments
has_many :course , through: :enrollments
end

Resources