Recursive many to many relationship on Rails - mysql

For my project, I have some Post linked to Category. What I want to achieve, is to have Category who are relatives to others. Like this :
c1 = Category.create(name: 'Television')
c2 = Category.create(name: 'TV')
c1.relatives << c1
I use a join table :
create_table :category_relative, id: false do |t|
t.belongs_to :category_1
t.belongs_to :category_2
end
add_index :category_relative, [:category_1_id, :category_2_id]
So far, I have tried this :
class Category < ActiveRecord::Base
has_and_belongs_to_many :relatives, class_name: 'Category',
join_table: 'category_relative', foreign_key: 'category_1_id',
association_foreign_key: 'category_2_id'
end
This is working, but only in a single way :
c1.relatives
=> []
c2.relatives
=> [#<Category:0x007fcc610b8418 id: 1, name: 'Television']
I know that I can add a relative for each entry, but this is too heavy for my database :
c1.relatives << c2
c2.relatives << c1
Do you have any idea ? Should I write the JOIN manually ?

You can try something like this
class Category < ActiveRecord::Base
has_many :category_relatives, dependent: :destroy
has_many :relatives, :through => :category_relative
has_many :inverse_category_relatives, :class_name => "categoryRelative", :foreign_key => "category_2_id", dependent: :destroy
has_many :inverse_relatives, :through => :inverse_category_relative, :source => :category
end
Through class:
class CategoryRelative < ActiveRecord::Base
belongs_to :category
belongs_to :relative, :class_name => "Category"
end
With this code you have a many to many relationship between the same class thourgh another

Related

Rails create data in has_many :through relation

I have these file and a CSV file. Now I want to
job.rb
class Job < ApplicationRecord
has_many :city_jobs
has_many :cities, through: :city_jobs
end
city.rb
class City < ApplicationRecord
has_many :city_jobs
has_many :jobs, through: :city_jobs
end
city_jobs.rb
class CityJob < ApplicationRecord
belongs_to :city
belongs_to :job
end
migration files
create_table :jobs do |t|
t.string :title
t.string :level
t.string :salary
t.string :other_salary
t.text :description
t.text :short_des
t.text :requirement
t.integer :category
t.datetime :post_date
t.datetime :expiration_date
t.references :company, foreign_key: true
t.timestamps
end
create_table :cities do |t|
t.string :name, unique: true
t.string :region
t.timestamps
end
create_table :city_jobs do |t|
t.references :city, foreign_key: true
t.references :job, foreign_key: true
t.timestamps
end
Import.rb
require "csv"
class JobsImport
def import_job
jobs = []
cities = []
job_columns = [:title, :level, :salary, :description, :short_des,
:requirement, :category, :company_id]
city_columns = [:name, :region]
CSV.foreach(Rails.root.join("lib", "jobss.csv"), headers: true) do |row|
cities << {name: row["company province"], region: "Việt Nam"}
jobs << JobCsv.new(row).csv_attributes
end
City.import city_columns, cities, on_duplicate_key_ignore: true
Job.import job_columns, jobs
puts "Data imported"
end
end
I have imported City and Job from CSV to database. Now how can I create data to City_jobs table that keep cities_id and jobs_id? Please help me! Thank you!
You can iterate through the CSV file again to connect the two tables.
CSV.foreach(Rails.root.join("lib", "jobss.csv"), headers: true) do |row|
city = City.find_by(name: row["company province"])
job = Job.find_by(JobsCsv.new(row).csv_attributes)
city.jobs << job
end

How to query rails way ? Rails 3.2

List of relationship between models:
class ErrorScope < ActiveRecord::Base
belongs_to :server
has_many :scope_to_fixflow_map
attr_accessible :id, :server_id, :error_codes, :scoping_method, :priority, :error_codes_is_wildcard_match
serialize :error_codes
.....
end
class ScopeToFixflowMap < ActiveRecord::Base
belongs_to :error_scope
attr_accessible :id, :server_id, :error_scope_id, :path, :fixflow_class_name
......
end
class Server < ActiveRecord::Base
has_many :error_scopes
......
end
schema.rb
create_table "error_scopes", :force => true do |t|
t.integer "server_id", :limit => 8, :null => false
t.text "error_codes", :null => false
t.text "scoping_method"
t.integer "priority", :null => false
t.boolean "error_codes_is_wildcard_match", :default => false
end
create_table "scope_to_fixflow_maps", :force => true do |t|
t.integer "server_id", :limit => 8, :null => false
t.integer "error_scope_id", :limit => 8, :null => false
t.string "path"
t.string "fixflow_class_name", :null => false
end
Now i have a sql query which gives me desired output:
SELECT fixflow_class_name
FROM error_scopes s
join scope_to_fixflow_maps m on s.id=m.error_scope_id
join servers serv on serv.id=s.server_id
where error_codes regexp 'error_scope_test'
and path = 'x'
and assettag = 'y'
What I tried so far. It works
ErrorScope.where("error_codes like ?", "%error_scope_test\n%").select {|tag| tag.server.assettag == "y"}[0].scope_to_fixflow_map.select {|y| y.path == "x"}[0].fixflow_class_name
using joins
ErrorScope.joins(:server, :scope_to_fixflow_map).where("error_codes LIKE ?", "%error_scope_test%").select {|tag| tag.server.assettag == "y"}[0].scope_to_fixflow_map.select {|y| y.path == "x"}[0].fixflow_class_name
I am sure there must be better way to do this query??
Something like this:
ErrorScope.joins(:server, :scope_to_fixflow_map)
.where("error_codes LIKE ?", "%error_scope_test%")
.where("servers.assettag='y'")
.where("scope_to_fixflow_maps.path='x'")
.select("scope_to_fixflow_maps.fixflow_class_name")
Not the rails way but quick and dirty:
ActiveRecord::Base.execute("SELECT fixflow_class_name
FROM error_scopes s
join scope_to_fixflow_maps m on s.id=m.error_scope_id
join servers serv on serv.id=s.server_id
where error_codes regexp 'error_scope_test'
and path = 'x'
and assettag = 'y'")
Returns back an array of hashes that you can work with

Active Record DB Modeling - Ruby on Rails

Ok guys, this might be a little bit confusing so stick with me. Let me start by introducing my tables. Basically I created four tables upon migration.
Students
Teachers
Subjects
Admin User
Here are my migration files:
Students:
def up
create_table :students, :id => false do |t|
t.integer "student_id",:primary_key => true
t.string "first_name", :limit => 25
t.string "last_name", :limit => 50
t.string "email", :default => ' ', :null => false
t.string "birthday"
t.string "subjects"
t.string "teachers"
t.string "username", :limit => 25
t.string "password_digest"
t.timestamps
end
Teachers:
def up
create_table :teachers, :id => false do |t|
t.integer "teacher_id", :primary_key => true
t.string "first_name"
t.string "last_name"
t.string "email", :default => ' ', :null => false
t.string "birthday"
t.string "subjects"
t.string "username", :limit => 25
t.string "password_digest"
t.timestamps
end
Subjects:
def up
create_table :subjects, :id => false do |t|
t.integer "subject_id", :primary_key => true
t.string "subject_name"
t.timestamps
end
end
Admin Users:
def up
create_table :admin_users, :id => false do |t|
t.integer "admin_user_id", :primary_key => true
t.string "username", :limit => 25
t.string "password_digest"
t.timestamps
end
end
So now let me get through the explanation. Basically:
one student can have many teachers
one teacher can have many students
one student can have many subjects
one teacher can teach many subjects
the admin can access all of this (create, edit, delete)
I created this fields and set them up on my models like this:
class Student < ApplicationRecord
has_and_belongs_to_many :subjects
has_and_belongs_to_many :teachers
has_many :admin_users
has_secure_password
self.primary_key = :student_id
end
class Teacher < ApplicationRecord
has_and_belongs_to_many :subjects
has_and_belongs_to_many :students
has_many :admin_users
has_secure_password
end
class Subject < ApplicationRecord
has_and_belongs_to_many :students
has_and_belongs_to_many :teachers
has_many :admin_users
# scope :search, lambda { |query| where(["name LIKE ?", "%#{query}%"])}
end
class AdminUser < ApplicationRecord
has_secure_password
scope :newest_first, lambda { order("created_at ASC") }
scope :oldest_first, lambda { order("created_at DESC") }
# scope :search, lambda { |query| where(["name LIKE ?", "%#{query}%"])}
end
Now I manually inserted data on mysql data record and then tried to pull up the records for student's subjects and teachers form fields.
How can I manage my database effectively esp teachers, students, and subjects??? Is there anything I need to do first to correlate the tables I have? Please help. Sorry for the long post. I am a newbie here. Appreciate your explanation (layman's term) and answers.
Check my models. Do I need to create a separate table to correlate teachers, students, and subjects?
Side Note: When I pull up my students and teachers field it gives me an error ActiveRecord_Associations_CollectionProxy:0x007f9c504361d0 ERROR.
I think this relation should work in your case:
Students:
def up
create_table :students, :id => false do |t|
t.integer "student_id",:primary_key => true
t.string "first_name", :limit => 25
t.string "last_name", :limit => 50
t.string "email", :default => ' ', :null => false
t.string "birthday"
t.string "subjects"
t.string "username", :limit => 25
t.string "password_digest"
t.timestamps
end
end
Ref: Generating auto increment with sequence 1001
Teachers:
def up
create_table :teachers, :id => false do |t|
t.integer "teacher_id", :primary_key => true
t.string "first_name"
t.string "last_name"
t.string "email", :default => ' ', :null => false
t.string "birthday"
t.string "subjects"
t.string "username", :limit => 25
t.string "password_digest"
t.timestamps
end
end
Subjects:
def up
create_table :subjects, :id => false do |t|
t.integer "subject_id", :primary_key => true
t.string "subject_name"
t.timestamps
end
end
Enrolled Subjects:
def up
create_table :enrolled_subjects, :id => false do |t|
t.integer "subject_id"
t.integer "teacher_id"
t.integer "student_id"
end
end
Model:
class Student < ApplicationRecord
has_many :enrolled_subjects
has_many :subjects, through: :enrolled_subjects
has_many :teachers, through: :enrolled_subjects
def teacher_names
self.teachers.map(&:first_name).join(", ")
end
end
class Teacher < ApplicationRecord
has_many :enrolled_subjects
has_many :subjects, through: :enrolled_subjects
has_many :students, through: :enrolled_subjects
end
class Subject < ApplicationRecord
has_many :enrolled_subjects
has_many :students, through: :enrolled_subjects
has_many :teachers, through: :enrolled_subjects
end
class EnrolledSubject < ActiveRecord::Base
belongs_to :student, foreign_key: :student_id
belongs_to :subject, foreign_key: :subject_id
belongs_to :teacher, foreign_key: :teacher_id
end
Example Repository

Rails has_many/belongs_to on custom database ActiveRecord::AssociationTypeMismatch got Fixnum

I have the database from another non-rails project so I have to deal with unordinary column names. I have the model Category:
self.primary_key = "categoryID"
has_many :products, foreign_key: "category", primary_key: "categoryID"
And the model Product:
self.primary_key = "productID"
belongs_to :category, foreign_key: "category", primary_key: "categoryID"
In the Product's table there's a foreign key category which stores a primary key of Category's table, which is categoryID. I'm trying to create a product in a console like that:
c = Category.last
p = c.products.create
And I get an error:
ActiveRecord::AssociationTypeMismatch: Category(#29703600) expected, got Fixnum(#17843240)
I tried some other ways to create a product where I could pass the Category instance there but it leads to other weird errors. So now I just want this way to work.
Where is a problem?
I think the problem is that you have category column (so Rails creates category method for it) and category association with the same name.
You can give some another name to association
I created test app
class CreateProducts < ActiveRecord::Migration
def change
create_table :products, id: false do |t|
t.integer :productID
t.integer :category
t.string :title
end
end
end
class CreateCategories < ActiveRecord::Migration
def change
create_table :categories, id: false do |t|
t.integer :categoryID
t.string :title
end
end
end
class Product < ActiveRecord::Base
self.primary_key = :productID
belongs_to :my_category, class_name: 'Category', foreign_key: :category
end
class Category < ActiveRecord::Base
self.primary_key = :categoryID
has_many :products, foreign_key: :category
end
This way the following code seems to work fine
c = Category.create categoryID: 1, title: 'First category'
c.products # => []
c.products.create productID: 1, title: 'First product'
c.products.create productID: 2, title: 'Second product'
c.products # => #<ActiveRecord::Associations::CollectionProxy [#<Product productID: 1, category: 1, title: "First product">, #<Product productID: 2, category: 1, title: "Second product">]>
p = Product.first
p.category # => 1
p.my_category # => #<Category categoryID: 1, title: "First category">

Create a custom many-to-many association - Ruby on Rails

I'm trying to make an application to store played FIFA games.
I'm having some trouble setting up the right associations.
I have 2 models at this time, User and Game.
SCHEMA:
ActiveRecord::Schema.define(version: 20160402112419) do
create_table "games", force: :cascade do |t|
t.integer "home_team_user_id"
t.integer "away_team_user_id"
t.string "home_score"
t.string "away_score"
t.integer "winner_id"
t.integer "loser_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "games_users", id: false, force: :cascade do |t|
t.integer "user_id"
t.integer "game_id"
end
add_index "games_users", ["user_id", "game_id"], name: "index_games_users_on_user_id_and_game_id"
create_table "users", force: :cascade do |t|
t.string "username"
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
MODELS:
class Game < ActiveRecord::Base
has_and_belongs_to_many :users
end
class User < ActiveRecord::Base
has_and_belongs_to_many :games
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
As you can see the "Games" table has 2 corresponding ID's:
home_team_user_id
away_team_user_id
These will store the user_id from the Users table, this is needed to calculate who's the winner corresponding with the score.
Console results:
irb(main):001:0> Game.last
Game Load (0.0ms) SELECT "games".* FROM "games" ORDER BY "games"."id" DESC LIMIT 1
=> #<Game id: 1, home_team_user_id: 1, away_team_user_id: 1, home_score: "1", away_score: "2", winner_id: 1, loser_id: 1, created_at: "2016-04-02 12:27:26", updated_at: "2016-04-02 12:27:26">
irb(main):002:0> game = Game.find(1)
Game Load (0.5ms) SELECT "games".* FROM "games" WHERE "games"."id" = ? LIMIT 1 [["id", 1]]
=> #<Game id: 1, home_team_user_id: 1, away_team_user_id: 1, home_score: "1", away_score: "2", winner_id: 1, loser_id: 1, created_at: "2016-04-02 12:27:26", updated_at: "2016-04-02 12:27:26">
irb(main):003:0> game.users
User Load (0.5ms) SELECT "users".* FROM "users" INNER JOIN "games_users" ON "users"."id" = "games_users"."user_id" WHERE "games_users"."game_id" = ? [["game_id", 1]]
=> #<ActiveRecord::Associations::CollectionProxy []>
I'm thinking now that the User.id needs to be linked to each individual corresponding id from the Games table.
How can I set this up? Do I need to use the has_many :through association?
UPDATE:
Could it be as simple as:
class User < ActiveRecord::Base
has_many :games, :foreign_key => "home_team_user_id"
has_many :games, :foreign_key => "away_team_user_id"
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
class Game < ActiveRecord::Base
belongs_to :user, :foreign_key => "home_team_user_id"
belongs_to :user, :foreign_key => "away_team_user_id"
end
Because actually a User has many games but in that game he only has one team, the home or away team. In this logic I assigned the user_id to one of the custom foreign fields.
You can achieve this like :
class User < ActiveRecord::Base
has_many :home_games, class_name: 'Game', foreign_key: 'home_team_user_id'
has_many :away_games, class_name: 'Task', foreign_key: 'away_team_user_id'
end
class Game < ActiveRecord::Base
belongs_to :home_user, class_name: "User", foreign_key: "home_team_user_id"
belongs_to :away_user, class_name: "User", foreign_key: "away_team_user_id"
# Rails anticipate foreign keys itself so, addig `foreign_keys` is not
# necessary in this class as we've already mentioned `belongs_to :home_user`
end