Rails -- whats the proper relationship model - ruby-on-rails

I've got a rails application built for schools. The users in the system are parents who track their childrens’ activities (aka family members or just members). Teachers are also users and can log in to participate in activities. The Member model is the place that the application uses to find participants. So that teachers can be found they are added to the Member model and for the same reason, parents are added as well.
A teacher added to this application would have one record in each table user, user_member, and member. A record in user to allow him to login, 1 record in member so he can be searchable, and 1 in user_member to make the association. In this case finding a user’s own member record is trivial. But if I were a parent with a login and 2 children in the system, James and Brian, one would find 3 records in the Members table, one for James, one for Brian and one for myself. I need to know which member record is mine, not James or Brian.
What’s the best way to model this? I’ve considered two options 1) there’s a foreign key in the user table that points to a user’s own member_id OR 2) the user_members table has a boolean called ‘own_member’ which indicates this user_id’s member_id is the member record for the user. Is there one that would be preferable? One more rails like? And how would I make the call build/create the associations?
The current relationships are modeled like this:
class User < ActiveRecord::Base
has_many :user_members
has_many :members, :through => :user_members
end
class UserMember < ActiveRecord::Base
belongs_to :user
belongs_to :member
end
class Member < ActiveRecord::Base
has_many :user_members
has_many :user, :through => :user_members
end

It sounds like the UserMember join model describes which members a user has privileges to access. This is a different concept than tracking which Member record is associated to a particular user. It sounds like a user would have a member record, and a member would belong to a user implying the following database structure:
class User < ActiveRecord::Base
has_many :user_members
has_many :members, :through => :user_members
has_one :member
end
class UserMember < ActiveRecord::Base
belongs_to :user
belongs_to :member
end
class Member < ActiveRecord::Base
has_many :user_members
has_many :user, :through => :user_members
belongs_to :user
end
This means adding another database column to the members table for "user_id". Creating and building the member record from a User instance could be done as follows:
user = User.new
user.build_member
user.create_member
More info on building through associations here: http://ar.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
You might consider creating callbacks to automatically create a member record on creation of a user record so you can skip manually building the associated record. An example would be:
# app/models/user.rb
class User < ActiveRecord::Base
before_create :build_member
def build_member
self.build_member
end
end
More information on callbacks here: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

Related

Ruby on Rails 4 - How to get a has_many association for a group of users?

I have the following setup in my database. We have users. Each user has many entries. Users also belong to organizations, through a table called organization_users.
class User < ActiveRecord::Base
has_many :entries
has_many :organization_users
has_many :organizations, :through => :organization_users
end
class Entry < ActiveRecord::Base
belongs_to :user
end
class Organization < ActiveRecord::Base
has_many :organization_users
has_many :users, :through => :organization_users
end
class OrganizationUser < ActiveRecord::Base
belongs_to :user
belongs_to :organization
end
Here's my question: for a given organization, I want to get a list of all the entries for the users in that organization. Is there a nice compact way to accomplish this? I know I can iterate over all users in the organization and get the entries, but I'm not sure if there is a nice rails-y way to do this.
You can do the following assuming you have a foreign key called organization_id in organization_users table as per your Model
Entry.joins(:user => :organization_users).where("organization_users.organization_id = ?", org_id)
Where org_id is the id of the given organization. This will give you all entries of all users in an organization
Try something like that :
my_org = Organization.find(id)
my_org.users.eager_load(:entries)
First you get the organization you want to query. Then via :through association you can directly retrieve all the users for that organization. And last using eager_load, in one query you get all the entries. The result will be an ActiveRecord::Relation.

Model Structure & has_many Association Migrations

I'm trying to set up models in such a way that Users can create Lessons and then other users can sign up for them.
Right now my models are set up like this:
class Lesson < ApplicationRecord
belongs_to :teacher, class_name: 'User'
has_many :students, class_name: 'User'
end
class User < ApplicationRecord
has_many :lessons
has_many :students, :through => :lessons
end
I want to be able to access the users signed up for a lesson by #lesson.students for example. I'd also like to be able to get all the lessons that a student is participating in (can't really see how I'd do this with my current set up).
Are my model associations right for how I'd like to use them? If so, how can I create the migrations to add the necessary references to my database models?
If you want the ability to create nested resources from it's parents then you have to add:
accepts_nested_attributes_for
to the parent model.
Also, I recommend you to read how to set up has_many through relationships, you need a join model for rails to do its magic and link the 2 models
Once you set everything up, create the join model (with it's respective foreign keys, one for lesson and the other for user) rails will take care of the associations between the models, allowing you to do things like:
User.last.lessons #lessons created by the last user
and
Lesson.first.users #users subscribed to a lesson, in this case the first one

Invite users to groups rails app

I'm building a simple rails app that allows users to login and create private lists for themselves, so far so good. I would like the user to then have the option to invite people to a certain list where these new users would have edit access to the tasks. This would be in the same vein as basecamp and trello in regards to adding users.
Where would I begin to start with this I have been wracking my brains and searching google and can't find any relevant tutorials of guidance.
Ok, so what about having
1) A users Table (model)
2) A lists table (model)
Model Associations
A user has many lists
A list belongs to a user
User table will have Foreign Key list_id (you will need to add this via a migration)
Thats just a start, I am assuming you know about resources ( the big 7 ) in rails? As you will be using this extensively
You can create a Membership table which will act as a join table between a User and List. You can then add an :admin attribute to the Membership model with a boolean type.
class List < ActiveRecord::Base
has_many :memberships
has_many :users, :through => :memberships
end
class User < ActiveRecord::Base
has_many :memberships
has_many :lists, :through => :memberships
end
class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :list
end

.build method not creating association in the join table

I have three Models setup with the following associations
class User < ActiveRecord::Base
has_many :faculties
has_many :schools, :through => :faculties
end
class School < ActiveRecord::Base
has_many :faculties
has_many :users, :through => :faculties
end
class Faculty < ActiveRecord::Base
belongs_to :user
belongs_to :school
end
and in my controller i go to create a school and assign the user
class SchoolsController < ApplicationController
def create
#school = current_user.schools.build(params[:school])
...
end
end
When I login and submit the form the flash displays success, but the association doesn't build on the join table.
I tried it inside the apps console and it builds the association just fine.
I've been stuck on this for a couple days now and I just cannot figure out what I am missing. Thank in advance for any and all advice
The build method does not save the object. You need to explicitly call #school.save.
Two things: If the schools association is :through a has_many association, you will have to select which parent the School exists through.
So, for instance, if you were to nest School resources under users as in /users/:id/faculties/:id you could create a school via current_user.faculties.find(params[:faculty_id]).schools.build(params[:school]).save
Based on the example code, it looks like the fundamental problem is that the has_many xxx, :through syntax is being used without specifying the id of the faculties record. Remember two things: 1) ActiveRecord doesn't natively support composite primary keys, and 2) you must call #save on associated records created using #build. If you remember these, you should be fine.

What is the best way to setup my tables and relationships for this use case?

1)A user can have many causes and a cause can belong to many users.
2)A user can have many campaigns and campaigns can belong to many users. Campaigns belong to one cause.
I want to be able to assign causes or campaigns to a given user, individually. So a user can be assigned a specific campaign. OR a user could be assigned a cause and all of the campaigns of that cause should then be associated with a user.
Is that possible? And could I set it up so that the relationships could be simplified like so:
User.causes = all causes that belong to a user
User.campaigns = all campaigns that belong to user whether through a cause association or campaign association
This should work.
class User < ActiveRecord::Base
has_many :causes, :through => :cause_users
has_many :campaigns, :through => :campaign_users
# other model stuff
class Cause < ActiveRecord::Base
has_many :users, :through => :cause_users
has-many :campaigns
# other model stuff
class Campaign < ActiveRecord::Base
belongs_to :cause
has_many :users, :through => :campaign_users
# other model stuff
class CampaignUser < ActiveRecord::Base
belongs_to :campaign
belongs_to :user
# other model stuff
class CauseUser < ActiveRecord::Base
belongs_to :cause
belongs_to :user
# other model stuff
has_many :through requires that you create a new model for each of these joins: campaign_users and cause_users, as is shown but it provides more functionality later on than has_and_belongs_to_many.
I would also suggest using better names than :campaign_users and :cause_users so the relationship is more meaningful.
I believe you should use the following:
class User < ActiveRecord::Base
has_and_belongs_to_many :causes
has_and_belongs_to_many :campaigns
end
class Cause < ActiveRecord::Base
has_and_belongs_to_many :users
has_many :campaigns
end
class Campaign < ActiveRecord::Base
has_and_belongs_to_many :users
belongs_to :cause
end
This way you can use
User.causes
User.campaigns
Cause.campaing
Cause.users
Campaign.users
Campaign.cause
You can read here about has_and_belongs_to_many relationship, here about has_one and here about belongs_to.
Let me know if this is what you want :]
Edit:
"I would still need User.campaigns to
be campaigns from a user's causes or
individual campaigns associated with a
user"
You can have a method on users model that returns all campaigns. Something like this:
def all_campaigns
self.campaigns + self.causes.collect{ |c| c.campaigns }
end
You can make :has_many :through associations between users and campaigns using a join model, and also between users and causes using the another join model. The you can make a :has_many :campaigns association in the causes model, putting a :belongs_to :cause in the campaign model.
But you won't be able to fetch all the users campaigns or causes by User.campaigns.orders or User.order.campaigns. You should make an iteration over the User.campaigns collection or User.causes, fetching Campaign.cause or Cause.capaigns. Or even making a custom SQL query, using joins and conditions to filter information in the joins.

Resources