Reputation: 1025
I am very new to rails and need help with seeding my tables. I have two tables "tracks" and "genres" and their migration files look like this
class CreateGenre < ActiveRecord::Migration[5.1]
def change
create_table :genres do |t|
t.string :rock
t.string :rap
t.string :jazz
t.string :alternative
t.references :track, foreign_key: true
t.timestamps
end
end
end
class CreateTracks < ActiveRecord::Migration[5.1]
def change
create_table :tracks do |t|
t.string :trackname
t.string :artist
t.timestamps
end
end
end
And here are the models
class Track < ApplicationRecord
has_one :genre
end
class Genre < ApplicationRecord
belongs_to :Track
end
Right now when I go to psql and check my tracks table, it has two columns trackname
and artist
. And I want to add genres for the tracks too but i dont know how to do it?
I did this
data = [
{
trackname: "hell yes",
artist: "beck"
},
{
trackname: "jailhouse rock",
artist: "elvis presley"
}
]
I am having problem figuring out how to seed the genre too when i am doing this. Where would i put it? please help.
Upvotes: 0
Views: 55
Reputation: 808
Sounds like you want to add genre
to your Tracks
table by running a migration.
Run:
rails generate migration add_column_to_tracks genre:string
Then run rake db:migrate
.
That should add the new field to the database.
Upvotes: 0
Reputation: 2344
From what I understand from your code I would try the following:
Track.create!(
trackname: "hell yes",
artist: "beck",
genre_attributes: {
rock: "true"
}
)
Upvotes: 1