I have a simple relationship
class School < ActiveRecord::Base
has_and_belongs_to_many :users
end
class User < ActiveRecord::Base
has_and_belongs_to_many :schools
end
A user can be part of many schools but at the same time a user might be the admin of a number of schools. I set up a many-to-many relationship to represent this however I'm not sure how I would distinguish between admins and simple users.
I initially thought of setting a table which has a school_id and a user_id and every entry will represent the school id and the user id of any admins that the school has however I'm not sure how I would represent this in rails or if it's the best way to solve this problem? And if it is, how do I access the table without a model associated to it?
What I mean by what I said above:
school_id user_id
1 3
1 4
Which means that the school with id 1 has 2 admins (3 and 4)
What you are looking for is a more complex many_to_many relationship between school and user called has_many :through. This relationship allows you to have many to many relationship with access to the table that represents the relationship. If you use that relationship, your models should look something like this:
class User < ActiveRecord::Base
has_many :school_roles
has_many :schools, through: :school_roles
end
class SchoolRole < ActiveRecord::Base
belongs_to :school
belongs_to :user
end
class School < ActiveRecord::Base
has_many :school_roles
has_many :users, through: :school_roles
end
And the migrations of those tables would look something like this:
class CreateSchoolRoles < ActiveRecord::Migration
def change
create_table :schools do |t|
t.string :name
t.timestamps null: false
end
create_table :users do |t|
t.string :name
t.timestamps null: false
end
create_table :school_roles do |t|
t.belongs_to :school, index: true
t.belongs_to :user, index: true
t.string :role
t.timestamps null: false
end
end
end
I would suggest to make the "role" field in the "school_roles" migration an integer and then use an enum in the model like so:
class SchoolRole < ActiveRecord::Base
belongs_to :school
belongs_to :user
enum role: [ :admin, :user ]
end
which allows you to add more roles in the future, but it's your call
combining polymorphic association with has_many :through in my opinion is best option.
Let's say you create supporting model SchoolRole, which
belongs_to :user
belongs_to :school
belongs_to :rolable, polymorphic:true
This way:
class School ...
has_many :administrators, :as => :schoolroles
has_many :users, :through => :administators
#school.administrators= [..., ...]
It is quite agile.
#user=#school.administrators.build()
class User
has_many :roles, :as => :rolable
def admin?
admin=false
self.roles.each do |r|
if r.role_type == "administator"
admin=true
break
end
end
admin
end
....
Related
I have the following associations set up:
class Book < ActiveRecord::Base
belongs_to :author
belongs_to :category
has_many :users_books
has_many :users, through: :user_books
end
and
class User < ActiveRecord::Base
has_many :users_books
has_many :books, through: :users_books
end
I created a join table migration as I ought to
class CreateUsersBooks < ActiveRecord::Migration[4.2]
def change
create_table :users_books do |t|
t.integer :user_id
t.integer :book_id
end
end
end
Now I need to create a method called check_out_book, that takes in a book and a due_date as arguments. When a user checks out a book, it should create a new UserBook record (or Checkout record or whatever you want to call you join table/model). That new UserBook record should have a attribute (and therefore table column) of returned? which should default to false. How would I go about creating this method and the migrations?
Your tablenames and your associations in Rails should always be singular_plural with the exception of the odd duckling "headless" join tables used by the (pretty useless) has_and_belongs_to_many association.
class CreateUserBooks < ActiveRecord::Migration[4.2]
def change
create_table :user_books do |t|
t.references :user
t.references :book
t.boolean :returned, default: false
end
end
end
class UserBook < ActiveRecord::Base
belongs_to :user
belongs_to :book
end
class Book < ActiveRecord::Base
belongs_to :author
belongs_to :category
has_many :user_books
has_many :users, through: :user_books
end
class User < ActiveRecord::Base
has_many :user_books
has_many :books, through: :user_books
end
But you should really use a better more descriptive name that tells other programmers what this represents in the domain and not just a amalgamation of the two models it joins such as Loan or Checkout.
I would also use t.datetime :returned_at to create a datetime column that can record when the book is actually returned instead of just a boolean.
If you want to create a join record with any additional data except the foreign keys you need to create it explicitly instead of implicitly (such as by user.books.create()).
#book_user = Book.find(params[:id]).book_users.create(user: user, returned: true)
# or
#book_user = current_user.book_users.create(book: user, returned: true)
# or
#book_user = BookUser.new(user: current_user, book: book, returned: true)
Say I have this:
class Picture < ApplicationRecord
belongs_to :imageable, polymorphic: true
end
class Employee < ApplicationRecord
has_many :pictures, as: :imageable
end
class Product < ApplicationRecord
has_many :pictures, as: :imageable
end
Does this require me to define a table exactly in the following way?
class CreatePictures < ActiveRecord::Migration[5.0]
def change
create_table :pictures do |t|
t.string :name
t.integer :imageable_id
t.string :imageable_type
t.timestamps
end
add_index :pictures, [:imageable_type, :imageable_id]
end
end
Or may I define a bit differently, with different columns or types, for example, that is, in a way I see more efficient? Will the polymorphic association remain functioning?
The polymorphic association only relates to the _type and _id pair of columns. Everything else is up to you.
So yes, you can add additional metadata if you like.
This follows on from my previous question
I have a user model with two self joins, seller and buyer.
I have an categories model, a seller has_and_belongs_to_many categories, as does a buyer.
How do I create the migration so I can do seller.categories and categories.buyers etc...
I thought it would be something like I have below but it doesn't work...
def change
create_table :categories_sellers do |t|
t.references :category
t.references :user
end
add_foreign_key :categories_sellers, :users, column: :trainer_id
add_index :categories_users, [:category_id, :seller_id]
add_index :categories_users, :seller_id
end
end
To answer your question, it looks like you just need to change t.references :user to t.references :seller.
That said, I would highly suggest modeling your project as such:
module User
extend ActiveSupport::Concern
has_many :category_users, as: :user
has_many :categories, through: :category_users
# include any common methods for buyers and sellers,
# basically your current User model
end
class Buyer < ActiveRecord::Base
include User
end
class Seller < ActiveRecord::Base
include User
end
class CategoryUser < ActiveRecord::Base
belongs_to :category
belongs_to :user, polymorphic: true
end
class Category < ActiveRecord::Base
has_many :category_users
has_many :buyers, through: :category_users, source: :user, source_type: 'Buyer'
has_many :sellers, through: :category_users, source: :user, source_type: 'Seller'
end
I know that may require some changes that you didn't anticipate, but in doing that, you get more natural methods such as:
category.buyers
category.sellers
buyer.categories
seller.categories
Under the hood, your join table will have columns like:
id -- the row id
category_id -- the category id, of course
user_id -- the id of the Buyer or Seller
user_type -- one of "Buyer" or "Seller" (or any other type you deem as "user")
To run the migrations:
User doesn't need one, it's not a model.
Buyer and Seller are pretty straightforward, old User model + Buyer/Seller model.
Category doesn't need one as it already exists.
CategoryUser:
def change
create_table :category_users do |t|
t.references :category
t.references :user, polymorphic: true
end
add_index :category_users, :category_id
add_index :category_users, [:category_id, :user_id]
add_index :category_users, [:category_id, :user_id, :user_type]
end
I haven't checked this personally but should be right, or close. The overall principle, though, is to make use of polymorphic associations to make a more natural association between "some kind of user" (whether it be a Buyer, Seller, or any other type of user you come up with) and a category. Then, you don't need to replicate the same sort of associations over and over again because the models slightly vary.
Here's more details on this approach:
http://guides.rubyonrails.org/association_basics.html#polymorphic-associations
I got the following use-case:
I got three types of Users: Advertisers, Publishers and Administrators. Each user has some common properties (like name or surname) but also several unique associations. The advertiser has an association with Ad(verttisement)s and Campaigns. Each of with is another model of its own.
My question is how would I go about and model that using ActiveRecords? What would the migration code look like?
Here are the model classes:
User:
class User < ActiveRecord :: Base
require 'pbkdf2'
require 'date'
has_many :messages
attribute :name, :surname, :email, :password_hash, :password_salt
attr_accessor :password, :password_confirmation, :type
attribute :user_since, :default => lambda{ Date.today.to_s }
[...]
end
Publisher:
class Publisher < User
has_many :websites
end
Advertiser:
class Advertiser < User
has_many :campaigns
has_many :ads
end
I got the following migration file to create the User:
class AddUser < ActiveRecord::Migration
def up
create_table :users do |t|
t.string :name
t.string :surname
t.string :email
t.string :password_hash
t.string :password_salt
t.date :user_since
t.string :type
end
create_table :messages do |t|
t.belongs_to :user
t.string :account_number
t.timestamps
end
end
def down
drop_table :user
end
end
How do I modify this file in order to incorporate the aforementioned associations?
Edit: Corrected the associations to use plural form.
Polymorphic relationships is one way to solve this, while another way would be to use Single Table Inheritance (STI). Each approach has its benefits and drawbacks, and your decision would probably depend in how different the subclasses of User would tend to be. The more drastically they would differ, the more the decision would tend toward polymorphic relationships.
Using STI approach:
# a single :users table
# one table for each of the other (non-user) models
class User < ActiveRecord::Base
has_many :messages
end
class Publisher < User
has_many :websites
end
class Advertiser < User
# if :campaign supports multiple user-types (polymorphic)
has_many :campaigns, :as => :user
# otherwise
has_many :campaigns
has_many :ads
end
class Message < ActiveRecord::Base
belongs_to :user
end
class Campaign < ActiveRecord::Base
# if multiple user-types will have campaigns
belongs_to :user # referential column should be :user_id
# otherwise
belongs_to :advertiser # referential column should be :advertiser_id
end
Using Polymorphic approach:
# there should be no :users table, as User will be an abstract model class
# instead make a table for each of all the other models
class User < ActiveRecord::Base
self.abstract_class = true
has_many :messages, :as => :messageable
end
class Publisher < User
has_many :websites
end
class Advertiser < User
has_many :campaigns
has_many :ads
end
class Message < ActiveRecord::Base
belongs_to :messageable, polymorphic: true # referential columns should be :messageable_id and :messageable_type
end
class Campaign < ActiveRecord::Base
# if multiple user-types will have campaigns
belongs_to :user, polymorphic: true # referential columns should be :user_id and :user_type
# otherwise
belongs_to :advertiser # referential column should be :advertiser_id
end
I have a model Shop and a model Customer. A shop can have many customers and a Customer
can buy stuff from many shops. for this relationship I've created a join model
ShopCustomers.
create_table :shop_customers do |t|
t.integer :shop_id
t.integer :customer_id
t.timestamps
end
Models
class Shop < ActiveRecord::Base
has_many :shop_customers, :dependent => true
has_many :customers, :through => shop_customers
has_many :customers_groups
end
class Customer < ActiveRecord::Base
has_many :shop_customers, :dependent => true
has_many :shops, :through => shop_customers
belongs_to :customers_group_membership
end
class ShopCustomer < ActiveRecord::Base
belongs_to :shop
belongs_to :customer
end
Shop owners want to be able to group customers and therefore I added another
model CustomersGroups.
class CustomersGroup < ActiveRecord::Base
belongs_to :shop
end
And the Customers are added to a group through another join model.
create_table :customers_group_memberships do |t|
t.integer :customers_group_id
t.integer :customer_id
end
class CustomersGroupMembership < ActiveRecord::Base
has_many :customers
belongs_to :customers_group
end
Is this the correct way of doing such kind of a relationship or this is a recipe
for doom and am I missing something that would make this not to work.
No, this is not the usual way of doing it. Have a look at the "has and belongs to many" association (AKA: HABTM). It will create the shops_customers join table for you and maintain it without you having to do it by hand.
here's a link to the apidock on HABTM: http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many