I have 2 Models with association has_many along with cascade property between them.
class ServicesBrandDetail < ApplicationRecord
has_many :services_brands, foreign_key: "brand_id", dependent: :delete_all
end
class ServicesBrand < ApplicationRecord
belongs_to :services_brand_details, foreign_key: "brand_id",
end
Migration for both files
class CreateServicesBrandDetails < ActiveRecord::Migration[6.1]
def change
create_table :services_brand_details do |t|
t.string :brand
t.string :mail_list
t.string :cc_list
t.timestamps
end
end
end
class CreateServicesBrands < ActiveRecord::Migration[6.1]
def change
create_table :services_brands do |t|
t.string :warehouse
t.references :brand, null: false, foreign_key: {to_table: :services_brand_details}
t.timestamps
end
end
end
Now I was able to create and save data in from ServicesBrandDetails model. but the Problem is when i create record from ServiceBrand It created record perfectly but i was not able to store data in DB.
record = ServicesBrandDetail.create(:brand => "a", :mail_list => 'abc#mail.com', :cc_list => 'def#mail.com')
record.save
Record successfully stored in DB.
child = record.services_brands.new(:warehouse => "in") <-- record was created successfully.
child.save
it give me error
C:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/activerecord-6.1.5/lib/active_record/inheritance.rb:237:in `compute_type': uninitialized constant ServicesBrand::ServicesBrandDetails (NameError)
Please follow proper Naming convention
This article might help - https://www.bigbinary.com/learn-rubyonrails-book/summarizing-rails-naming-conventions
In ServiceBrand Model
class ServiceBrand < ApplicationRecord
belongs_to :brand, class_name: 'ServiceBrandDetail'
end
belongs_to should be foreign key name i.e brand in your case
You can delete existing models and tables from your codebase and try below one. (I've tested)
class ServiceBrandDetail < ApplicationRecord
has_many :service_brands, foreign_key: :brand_id, dependent: :delete_all
end
class ServiceBrand < ApplicationRecord
belongs_to :brand, class_name: 'ServiceBrandDetail'
end
Migration for both files
class CreateServiceBrandDetails < ActiveRecord::Migration[6.1]
def change
create_table :service_brand_details do |t|
t.string :brand
t.string :mail_list
t.string :cc_list
t.timestamps
end
end
end
class CreateServiceBrands < ActiveRecord::Migration[6.1]
def change
create_table :service_brands do |t|
t.string :warehouse
t.references :brand, null: false, foreign_key: {to_table: :service_brand_details}
t.timestamps
end
end
end
Then try to create model objects which you tried in your question. It will work 👍🏽
In your model ServicesBrand you have to use singular association name for belongs_to
Change this belongs_to :services_brand_details to this belongs_to :services_brand_detail
class ServicesBrand < ApplicationRecord
belongs_to :services_brand_detail, foreign_key: "brand_id"
end
Related
I wonder is it ok to have like 2 associations with the same table. For example:
class CreateTeams < ActiveRecord::Migration[6.0]
def change
create_table :teams do |t|
t.string :name, null: false
t.references :manager, foreign_key: { to_table: 'users' }
end
end
end
class CreateUsers < ActiveRecord::Migration[6.0]
def change
create_table :users do |t|
t.string :name, null: false
t.references :team
end
end
end
class Team < ApplicationRecord
has_many :users
belongs_to :manager, class_name: 'User', foreign_key: 'manager_id'
end
class User < ApplicationRecord
belongs_to :team
has_one :child_team, class_name: 'Team' # bad name, but just for example
end
Or it would be better to create a join table with team_id, user_id, and member_type?
Ruby/Rails versions do not matter but let's assume Ruby is 2.7.0 and Rails is 6.0.0
From a technical point of view - that's perfectly fine, but be careful with possible foreign key loop in the future.
This is more a question of architecture and your predictions of how system will evolve. A many-to-many relation with a explicit join model is more flexible. For example:
does manager always belong to the team? with a join table it's easier to fetch "all users from the team, no matter the role" or "all the teams a person has relation to, also no matter the role"
if there will be other roles or multiple people at same position - join table will also come handy
What you have seems fine.
Though a join table would be more flexible to provide more roles. This also avoids having a circular dependency in setting up teams and users.
class CreateTeams < ActiveRecord::Migration[6.0]
def change
create_table :teams do |t|
t.string :name, null: false
t.timestamps
end
end
end
class CreateUsers < ActiveRecord::Migration[6.0]
def change
create_table :users do |t|
t.string :name, null: false
t.timestamps
end
end
end
class CreateTeamMembers < ActiveRecord::Migration[6.0]
def change
create_table :team_members do |t|
t.belongs_to :user, null: false, foreign_key: true
t.belongs_to :team, null: false, foreign_key: true
t.integer :role, null: false
t.timestamps
# Enforce one manager per team
t.index [:team_id],
name: :one_manager,
unique: true,
where: "role = 0"
end
end
end
class TeamMember < ApplicationRecord
enum role: { manager: 0, player: 1, fan: 2 }
belongs_to :user
belongs_to :team
end
class Team < ApplicationRecord
has_many :users, through: :team_members
has_many :team_members, dependent: :destroy
has_one :manager, -> { where(role: :manager) }, class_name: "TeamMember"
has_many :players, -> { where(role: :player) }, class_name: "TeamMember"
has_many :fans, -> { where(role: :fan) }, class_name: "TeamMember"
end
class User < ApplicationRecord
has_many :team_memberships, dependent: :destroy, class_name: "TeamMember"
has_many :teams, through: :team_memberships
end
You could even potentially take advantage of single table inheritance to differentiate your users by their role.
This is something you could migrate to later if necessary.
I find this issue when I try to save the a team, how can I solve it? I am trying to deal with these associations for so long, if you guys do other issues, just let me know, please (this association has been a nightmare).
Here are the models
class Field < ApplicationRecord
end
class Game < ApplicationRecord
belongs_to :field
belongs_to :organiser
has_one :team
has_many :players, through: :team
end
class Organiser < ApplicationRecord
has_many :games
end
class Player < ApplicationRecord
has_many :teams
has_many :games, through: :teams
end
class Team < ApplicationRecord
has_many :players
belongs_to :game
end
Here are the migrations
class CreateOrganisers < ActiveRecord::Migration[5.2]
def change
create_table :organisers do |t|
t.string :name
t.string :email
t.integer :age
t.timestamps
end
end
end
class CreatePlayers < ActiveRecord::Migration[5.2]
def change
create_table :players do |t|
t.string :name
t.integer :age
t.string :address
t.timestamps
end
end
end
class CreatePlayers < ActiveRecord::Migration[5.2]
def change
create_table :players do |t|
t.string :name
t.integer :age
t.string :address
t.timestamps
end
end
end
class CreateFields < ActiveRecord::Migration[5.2]
def change
create_table :fields do |t|
t.string :location
t.string :transports
t.timestamps
end
end
end
class CreateGames < ActiveRecord::Migration[5.2]
def change
create_table :games do |t|
t.references :field, foreign_key: true
t.references :organiser, foreign_key: true
t.integer :size
t.timestamps
end
end
end
class CreateTeams < ActiveRecord::Migration[5.2]
def change
create_table :teams do |t|
t.references :player, foreign_key: true
t.references :game, foreign_key: true
t.timestamps
end
end
end
class AddTeamToGames < ActiveRecord::Migration[5.2]
def change
add_column :games, :team, :reference
end
end
The idea is to make sure that each game will have a team of certain people. I want to access the people through game.team.player
Your migrations doesn't have any kind of references to connect these tables.
For example Game has_one :team is not going to create this references for you, to call game.team needs a column called game_id in teams table.
To add the reference you can create a migration for it:
rails g migration AddGameToTeams game:references
This will create that migration file may look like this:
class AddGameToTeams < ActiveRecord::Migration
def change
add_reference :teams, :game, index: true
end
end
Depending in the version you running rails this migration file may differ a little with adding an extra line regarding foreign_key.
Run the generated migration with rails db:migrate and it should work.
You need to apply the same concept to the rest of your tables.
Hope this helps.
I am trying the following -
I have Models: Tales, Books, Keywords
class Tale < ActiveRecord::Base
has_many :tale_culture_joins
has_many :cultures, through: :tale_culture_joins
has_many :tale_purpose_joins
has_many :purposes, through: :tale_purpose_joins
has_many :tale_book_joins
has_many :books, through: :tale_book_joins
has_many :tale_keyword_joins
has_many :keywords, through: :tale_keyword_joins
class Book < ActiveRecord::Base
has_many :tale_book_joins
has_many :tales, through: :tale_book_joins
end
class TaleBookJoin < ActiveRecord::Base
belongs_to :tale
belongs_to :book
end
class Keyword < ActiveRecord::Base
has_many :tale_keyword_joins
has_many :tales, through: :tale_keyword_joins
end
class TaleKeywordJoin < ActiveRecord::Base
belongs_to :tale
belongs_to :keyword
end
These are the migrations
class CreateTales < ActiveRecord::Migration
def change
create_table :tales do |t|
t.text :name, null: false, unique: true
t.boolean :exists, default: nil
t.timestamps null: false
end
end
end
class CreateBooks < ActiveRecord::Migration
def change
create_table :books do |t|
t.text :name, null: false, unique: true
t.boolean :exists, default: nil
t.timestamps null: false
end
end
end
class CreateKeywords < ActiveRecord::Migration
def change
create_table :keywords do |t|
t.text :name, null: false, unique: true
t.boolean :exists, default: nil
t.timestamps null: false
end
end
end
What I want to happen is that everytime i delete a join between (Tale, Book) or (Tale,Keyword) through following method
tale_instance_object.book_ids = []
It should go and check if the books for whom the relations have been broken have any other tale relations. If not then set :exists in Book object instance to false.
I am able to do this through controller code.
Wondering how CallBacks or ActiveModel can be used
Join classes should only really be used when the relation is an object on its own.
Consider these cases:
doctors -> appointments <- patients
years -> days <- hours
In these cases the relation object has data of its own (appointments.time, days.weekday) and logic. Otherwise you are just wasting memory since a object has to instantiated for every relation. Use has_and_belongs_to instead.
class Tale < ActiveRecord::Base
# has_and_belongs_to_many :cultures
# has_and_belongs_to_many :purposes
has_and_belongs_to_many :books
has_and_belongs_to_many :keywords
after_destroy :update_books!
end
class Book
has_and_belongs_to_many :tales
def check_status!
self.update_attribute(status: :inactive) unless books.any
end
end
class Keyword
has_and_belongs_to_many :tales
end
Also exists is a really bad naming choice for a model field since it collides with Rails built in exists? methods. This will have unexpected consequences.
A better alternative would be to use an integer combined with an enum.
class Book
# ...
enum :status [:inactive, :active] # defaults to inactive
end
class CreateBooks < ActiveRecord::Migration
def change
create_table :books do |t|
t.text :name, null: false, unique: true
t.integer :status, default: 0
t.timestamps null: false
end
end
This will also add the methods book.inactive? and book.active?.
You could add a callback to Tale which tells Book to update when a tale is updated but this code really stinks since Tale now is responsible for maintaining state of Book.
class Tale < ActiveRecord::Base
# ...
after_destroy :update_books!
def update_books!
self.books.each { |b| b.check_status! }
end
end
class Book
has_and_belongs_to_many :tales
def check_status!
self.update_attribute(status: :inactive) unless tales.any?
end
end
A better alternative to add a callback on Books or to do it in the controller when destroying a tale:
class Book
has_and_belongs_to_many :tales
before_save :check_for_tales!, if: -> { self.tales_changed? }
def check_for_tales!
self.status = :inactive unless self.tales.any?
end
end
I have two models: Users and Microposts. There is an association between one-to-many. I would like to add to Microposts field replic_to and replics_from to Users, and association with many-to-many relationships that will not only be stored in the model Microposts the author, but the user ID, which is addressed to the message. Because of already having associations between models, I think you need to specify the force field as FK for new association. I ask you to show how it can be done. Thank you in advance.
This`s sources:
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :email
t.timestamps
end
end
end
class CreateMicroposts < ActiveRecord::Migration
def change
create_table :microposts do |t|
t.string :content
t.integer :user_id
t.timestamps
end
add_index(:microposts, [:user_id, :created_at]);
end
end
class User < ActiveRecord::Base
....
has_many(:microposts, dependent: :destroy);
....
end
class Micropost < ActiveRecord::Base
....
belongs_to :user;
....
end
Add to micropost.rb
belongs_to :replics_to, class_name: 'User'
The corresponding field should be
add_column :microposts, :replics_to_id, :integer
For user.rb
has_many :replics_from, class_name: 'User', foreign_key: 'replics_to_id'
Very new to Rails, have managed a few simple projects, but now stepping into more complex associations between tables and was hoping for some help.
The scenario can best be related to a sports match. Let's say we have
1) A Team (has_many players)
2) A Player (belongs_to team)
3) A Match -- now it gets tricky.
A Match will have: 2 teams, and 22 players (11 on each side) that take part in it. Also, associated with each player, will be their scores for the match (for example, Shots on goal, Goals scored, Points, etc.)
What would be the best practice to create this kind of association? Any tips would be greatly appreciated.
Models
app/models/team.rb
class Team < ActiveRecord::Base
has_many :players, inverse_of: :team
has_many :team_matches
has_many :matches, through: :team_matches
end
app/models/player.rb
class Player < ActiveRecord::Base
belongs_to :team, inverse_of: :player
has_many :player_matches
has_many :matches, through: :player_matches
end
app/models/match.rb
class Match < ActiveRecord::Base
has_many :players, through: :player_matches
has_many :teams, through: :team_matches
end
app/models/team_match.rb
class TeamMatch < ActiveRecord::Base
belongs_to :team
belongs_to :match
end
app/models/player_match.rb
class PlayerMatch < ActiveRecord::Base
belongs_to :player
belongs_to :match
end
Migrations
db/migrate/create_matches.rb
class CreateMatches < ActiveRecord::Migration
def change
create_table :matches do |t|
t.datetime :happened_at
t.timestamps
end
end
end
db/migrate/create_players.rb
class CreatePlayers < ActiveRecord::Migration
def change
create_table :players do |t|
t.string :name
t.timestamps
end
end
end
db/migrate/create_teams.rb
class CreateTeams < ActiveRecord::Migration
def change
create_table :teams do |t|
t.string :name
t.timestamps
end
end
end
db/migrate/create_player_matches.rb
class CreatePlayerMatches < ActiveRecord::Migration
def change
create_table :player_matches do |t|
t.integer :match_id
t.integer :player_id
t.integer :player_shots_on_goal
t.integer :player_goals_scored
t.timestamps
end
end
end
db/migrate/create_team_matches.rb
class CreateTeamMatches < ActiveRecord::Migration
def change
create_table :team_matches do |t|
t.integer :match_id
t.integer :team_id
t.integer :team_points
t.timestamps
end
end
end
Edit1: #Mischa should share credit here! :)
Edit2: Sorry about the many versions, I totally underestimated this problem.
Player Has and belongs to Many Match
That table should contain the details of the player playing that match. For example for which team he played, from which minute (since players can change) etc.