Habtm join tables for a model with a self join - ruby-on-rails

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

Related

how to create a record for a join table?

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)

Ruby on Rails - Polymorphic associations + joint table + reference the same model twice?

I am having a hard time using polymorphic associations in a joint table where one option could lead to the association of two instances of the same table. I am relatively new to programming so I hope my question makes sense.
Basically, I have 3 models where my aim is to make associations between different products:
Product
ExtrenalProduct
Integration (polymorphic)/joint table
The Integration table will link 2 Products or 1 Product and 1 ExternalProduct
Here is my migration file:
class CreateIntegrations < ActiveRecord::Migration[5.1]
def change
create_table :integrations do |t|
t.references :main_product
t.belongs_to :integratable, polymorphic: true
t.timestamps
end
add_index :integrations, [:integratable_id, :integratable_type]
add_foreign_key :integrations, :products, column: :main_product_id, primary_key: :id
end
end
Here is my Integration Model:
class Integration < ApplicationRecord
belongs_to :integratable, polymorphic: true
belongs_to :main_product, class_name: 'Product'
end
Here is my ExternalProduct Model:
class ExternalProduct < ApplicationRecord
has_many :integrations, as: :integratable
end
Here is my Product Model:
has_many :integrations, class_name: 'Integration', foreign_key: 'main_product_id', dependent: :destroy
has_many :integrations, as: :integratable
My question is regarding the way I can query all Integrations from #product. As for now, I have to build a custom method:
def all_integrations
Integration.where(main_product_id: id).or(Integration.where(integratable_type: 'Product', integratable_id: id))
end
I would like to be able to do a: #product.integrations (which currently retrieves an empty array)
Any clue on what I am doing wrong or how I could make this code DRY? I feel I am missing something.
Thanks for reading!

Loose associations in ActiveRecord

I'm new to Ruby on Rails and I'm trying to build a relationship between the classes Club, Sponsor and Match.
The relationhip has to be like:
One Club has zero to many Sponsors
One Sponsor has zero to many Matches
One Match has zero to many Sponsors
My models look like this
class Match < ApplicationRecord
belongs_to :team
has_many :matchplayers
has_many :players, through: :matchplayers
has_many :sponsors
end
class Club < ApplicationRecord
has_many :teams
has_many :sponsors
accepts_nested_attributes_for :teams, :reject_if => :all_blank, :allow_destroy => true
end
class Sponsor < ApplicationRecord
belongs_to :club
end
and my migrations file for the Sponsor model looks like this:
class CreateSponsors < ActiveRecord::Migration[5.1]
def change
create_table :sponsors do |t|
t.text :name
t.text :url
t.text :imgUrl
t.references :club, foreign_key: true
t.timestamps
end
add_reference :matches, :sponsor, index: true
add_foreign_key :matches, :sponsor
end
end
I have no problems retrieving sponsors for each club instance but I'm having trouble retrieving the sponsors associated with each match.
In my matches_controller.rb I have this
def show
#match = Match.find(params[:id])
render :json => #match.to_json(:include => [:players, :sponsors])
end
But when I try to run it the script fails. with the error message "no such column: sponsors.match_id" as the script tries to run the following SQL statement
SELECT "sponsors".* FROM "sponsors" WHERE "sponsors"."match_id" = ?
What I'd really like it to do would be to run the following statement
SELECT "sponsors".*
FROM "sponsors"
LEFT JOIN "matches"
ON "matches"."sponsor_id" = "sponsors"."id"
WHERE "matches"."id" = ?
And placing the resulting array into the output JSON's "sponsors" attribute.
I have been looking into the different Active Record association types and I feel like the type of association I need for this task is looser than the ones described in the documentation.
You need many-to-many relationship. In rails where are 2 ways to do this. You can read about this here. In general you will need to add has_and_belongs_to_many to Sponsor and to Match. And create 'join-model' which will contain match_id + sponsor_id. In this way ActiveRecord will be able to create suitable SQL query due to 'join-table'.

How to set up an admin user in rails

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
....

Ruby on Rails has_many :through Associations. Would this work?

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

Resources