Activerecord many-to-many relationship not working - ruby-on-rails

I'm working on a twitter clone and have been having trouble with some of my associations. I want a user to have many tweets. My tweets will have a many-to-many relationship with hashtags, so in theory I want to be able to call User.find(1).hashtags and have a list of the user's hashtags (edit: solved this issue). I also am having trouble pushing hashtags into a specific tweet.
Here are my models:
class User < ActiveRecord::Base
has_many :tweets
end
class Tweet < ActiveRecord::Base
belongs_to :user
has_and_belongs_to_many :hashtags
end
class Hashtag < ActiveRecord::Base
has_and_belongs_to_many :tweets
end
Here are my migrations:
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :username
t.string :email
t.string :password
t.timestamps
end
end
end
class CreateTweets < ActiveRecord::Migration
def change
create_table :tweets do |t|
t.string :content
t.belongs_to :user
t.timestamps
end
end
end
class CreateHashtags < ActiveRecord::Migration
def change
create_table :hashtags do |t|
t.string :tag
t.timestamps
end
end
end
class CreateHashtagsTweets < ActiveRecord::Migration
def change
create_table :hashtags_tweets, id: false do |t|
t.references :hashtag
t.references :tweet
end
end
end
Any help would be greatly appreciated! Thanks!

Related

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.

Category has_many videos, video belongs_to_many categories

I'm doing like a little video site like 9gagtv style
and videos in the site has a category so the user can find all the Tech videos for example
but some videos belongs_to_many categories like when a video is about tech but also is funny so it will show up in both categories videos and i'm not sure how to do this?
would it require more than one t.references in videos table ? how would the relationship go?
category.rb
class Category < ApplicationRecord
has_many :videos
end
video.rb
class Video < ApplicationRecord
belongs_to :category
end
category migrations
class CreateCategories < ActiveRecord::Migration[5.0]
def change
create_table :categories do |t|
t.string :title
t.timestamps
end
end
end
video migrations
class CreateVideos < ActiveRecord::Migration[5.0]
def change
create_table :videos do |t|
t.string :url
t.string :title
t.text :description
t.integer :duration
t.references :category, foreign_key: true
t.timestamps
end
end
end
You can use has_and_belongs_to_many
to create many-to-many association through the third table.
Models:
class Category < ApplicationRecord
has_and_belongs_to_many :videos
end
class Video < ApplicationRecord
has_and_belongs_to_many :categories
end
Migrations:
class CreateCategories < ActiveRecord::Migration[5.0]
def change
create_table :categories do |t|
t.string :title
t.timestamps
end
end
end
class CreateVideos < ActiveRecord::Migration[5.0]
def change
create_table :videos do |t|
t.string :url
t.string :title
t.text :description
t.integer :duration
t.timestamps
end
end
end
class CreateCategoriesVideos < ActiveRecord::Migration[5.0]
def change
create_table :categories_videos do |t|
t.references :category, index: true
t.references :video, index: true
end
end
end
I think what you're looking for is has_and_belongs_to_many relation (see more)
It should look something like that
Category
class Category < ApplicationRecord
has_and_belongs_to_many:videos
end
Video
class Video < ApplicationRecord
belongs_to :category
end
And migration
class CreateCategoriesVideosJoinTable < ActiveRecord::Migration
def change
create_table :categories_videos, id: false do |t|
t.integer :category_id
t.integer :video_id
end
end
end

How to make has_many work?

Models:
class Game < ActiveRecord::Base
belongs_to :manufacturer
end
.
class Manufacturer < ActiveRecord::Base
has_many :games
end
Migrations:
class CreateManufacturers < ActiveRecord::Migration
def change
create_table :manufacturers do |t|
t.string :name
t.timestamps null: false
end
end
end
.
class CreateGames < ActiveRecord::Migration
def change
create_table :games do |t|
t.string :name
t.references :manufacturer, index: true, foreign_key: true
t.timestamps null: false
end
end
end
When I enter m = Game.find(2).manufacturer this works and gives me the manufacturer name. But when I give g = Manufacturer.find(1).games console throws many errors. Why does not the has_many work?
Or
How do I get all the games developed by the 1st manufacturer?
Error shown:
NoMethodError: undefined method `games' for #<Manufacturer:0x007f996dc75368>

Ruby on rails does not create foreign keys on database

Is it normal that rails doesn't create the foreign keys on database? Or I'm doing something wrong?
I have these models:
class City < ActiveRecord::Base
has_many :users
end
class User < ActiveRecord::Base
belongs_to :city
end
and their respective migrations:
class CreateCities < ActiveRecord::Migration
def change
create_table :cities do |t|
t.string :name
t.timestamps
end
end
end
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.references :city, index: true
t.timestamps
end
end
end
That's correct. Rails doesn't automatically add foreign keys, you have to specify it yourself in the migration like you have.
t.references :city is effectively the same as t.integer :city_id.
Are you saying that even though are specifying a foreign key, that you aren't seeing the results?

Rails set_primary_key breaks association in intermediary model callback

I'm stumped. I keep getting a Called id for nil error Assume i have the following models:
class User < ActiveRecord::Base
self.primary_key = 'name'
attr_accessible :name
has_many :projects, :through => :user_projects
has_many :user_projects
end
class UserProject < ActiveRecord::Base
belongs_to :user
belongs_to :project
after_save do |r|
puts r.user.id #<<<<<error here!
end
end
class Project < ActiveRecord::Base
attr_accessible :name#, :body
has_many :user_projects
has_many :users, :through=> :user_projects
# attr_accessible :title, :body
end
and the following migrations:
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.timestamps
end
end
end
class CreateProjects < ActiveRecord::Migration
def change
create_table :projects do |t|
t.string :name
t.timestamps
end
end
end
class CreateUserProjects < ActiveRecord::Migration
def change
create_table :user_projects do |t|
t.references :user
t.references :project
t.timestamps
end
end
end
running something like :
#project = Factory.create(:project)
#user = Factory.create(:user)
#user.projects << #project
I would get this:
RuntimeError: Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
Why does the the after_save callback break and what can i do to fix it? It seems like i can't refer to the associated user object from the callback at all. However, if i remove
self.primary_key = 'name'
from the User model, everything works fine. I'm missing something but i don't know what.
Thanks in advance! btw im on rails 3.2.6.
Try to set id to false in your migration like this :
class CreateUsers < ActiveRecord::Migration
def change
create_table :users, :id => false do |t|
t.string :name
t.timestamps
end
end
end
Thanks for the inspiration Dougui! i figured it out. the t.references :project helper defaults the foreign_key to an integer. I changed it manually to the correct type. So now it works!
YaY
class CreateUserProjects < ActiveRecord::Migration
def change
create_table :user_projects do |t|
t.string :user_id #<<<<<<< STRING!!
t.references :project
t.timestamps
end
end
end

Resources