has_many through and has_many - ruby-on-rails

I am a complete rookie in rails development so expect the worst. Up until now I have read a lot about this but I am still unable to find out what I did wrong.
I have difficulties finding the right way to create a model and migration that would enable the relationship described in the model below.
Right now this is my migration:
class CreateCoaches < ActiveRecord::Migration
def change
create_table :coaches do |t|
t.string :first_name
t.string :last_name
t.string :email
t.timestamps
end
create_table :pupils do |t|
t.string :first_name
t.string :last_name
t.string :email
t.belongs_to :coach
t.timestamps
end
create_table :talks do |t|
t.belongs_to :coach
t.belongs_to :pupil
t.datetime :talk_date
t.timestamps
end
end
end
And this is the models:
class Coach < ActiveRecord::Base
has_many :talks
has_many :pupils, through: :talks
has_many :pupils
end
class Patient < ActiveRecord::Base
has_many :talks
belongs_to :coach
has_many :coaches, through: :appointments
end
class Talk < ActiveRecord::Base
belongs_to :pupil
belongs_to :coach
end
This is the rspec test I am trying to execute (I hope it does not make your eyes bleed...)
require 'spec_helper'
describe Coach do
before(:each) do
#coach = Coach.create!(first_name: "Förnamn", last_name: "Efternamn")
end
it "creates a Coach" do
Coach.create!(first_name: "Andy", last_name: "Lindeman")
expect(Coach.find_by_first_name("Andy").first_name).to eq("Andy")
end
it "creates a Coach and a pupil" do
#coach.pupils << Pupil.create!(first_name:"Donald", last_name:"Duck")
expect(#coach.pupils[0].first_name).to eq "Donald"
end
end
And the error:
Failure/Error: #coach.pupils << Pupil.create!(first_name:"Donald", last_name:"Duck")
LoadError:
Unable to autoload constant Pupil, expected /home/elgrego/Projects/Coachen/app/models/pupil.rb to define it
Regards
Elgrego

I think you misspelled your model. You're calling it Patient but I think you meant Pupil. Also, it's better to user t.references rather than belongs_to in your migrations. But it looks like you're doing well so far. You might be making some other errors but I would fix that and see what else is wrong.

Just to add to freddyrangel's answer.
Modify your models as below:
class Coach < ActiveRecord::Base
has_many :pupils
has_many :talks, through: :pupils
end
class Pupil < ActiveRecord::Base
has_many :talks
belongs_to :coach
end
I would suggest you to read about Active Record Associations

Related

rails - can't save data in associated models in RoR

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

ActiveModel::MissingAttributeError: can't write unknown attribute `team_id`

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.

How add association with custom FK in Ruby on Rails?

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'

Tables associations best practices in Rails?

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.

Problem with has_many :through Association in Ruby on Rails

I've got a problem with a has_many :through association, i cant call the u1.UsersProfileAttributes.find_by_ProfileAttribute_name("icq") method, rails means that this method doesn't exist. The method u1.UsersProfileAttributes.find_by_ProfileAttribute_id(3) works correctly. u1 is a user object. I don't know whats the problem, because my associations seems to be okay. Have a look:
class ProfileAttribute < ActiveRecord::Base
has_many :UsersProfileAttributes
has_many :users, :through => :UsersProfileAttributes
end
class User < ActiveRecord::Base
has_many :UsersProfileAttributes
has_many :ProfileAttributes, :through => :UsersProfileAttributes
end
class UsersProfileAttribute < ActiveRecord::Base
belongs_to :user
belongs_to :ProfileAttribute
end
My Migration file:
class CreateProfileAttributes < ActiveRecord::Migration
def self.up
create_table :profile_attributes do |t|
t.string :name
t.integer :profile_group_id
t.timestamps
end
create_table :users_profile_attributes do |t|
t.integer :user_id
t.integer :ProfileAttribute_id
t.string :value
end
end
def self.down
drop_table :profile_attributes
drop_table :users_profile_attributes
end
end
You need to query ProfileAttributes, not UsersProfileAttributes. This should work for you: u1.ProfileAttributes.find_by_name('icq')
u1.UsersProfileAttributes.find_by_ProfileAttribute_id(3) works because ProfileAttribute_id is an attribute of UsersProfileAttribute ... so ActiveRecord builds you a dynamic finder.
u1.UsersProfileAttributes.find_by_ProfileAttribute_name("icq") does not work because ProfileAttribute_name is not an attribute of UsersProfileAttribute.

Resources