0

I'm trying to add a users username to a song.

app/models/user.rb

class User < ActiveRecord::Base
  has_many :songs 
  ...
end

app/models/song.rb

class Song < ActiveRecord::Base
  belongs_to :user
  ...
end

I'm trying to make a migration to add a username table to my songs table

class AddUsernameToSongs < ActiveRecord::Migration
  def change
    add_column :songs, :username, :string
  end
end

But I keep getting an uninitialized constant error when I try to run rake db:migrate

I want to be able to on each song call

<%= song.username %> 

To post the author of the track.

I'm using devise to set up my users and the devise table already has a username field.

3
  • 1
    Post your full migration error and the filename of your migration. Lastly, song.username isn't magic. You need to be sure you assign a value to that attribute. Commented Feb 17, 2016 at 2:36
  • Your belongs_to :user line in song.rb is going to assume you have a user_id column on the songs table. Do you have this foreign key column? Commented Feb 17, 2016 at 3:09
  • Don't add a username column to your song table. If you have the relation setup correctly, you should be able to access the username by doing song.user.username Commented Feb 17, 2016 at 3:17

1 Answer 1

1

Its a better idea to link to the song to a user by id than just the username.

if you don't already have this. I think that you do as you say you have an association.

class AddUserToSongs < ActiveRecord::Migration
  def change
    add_column :songs, :user_id, :integer
  end
end

In your song model you can add a method called ** author **

class Song < ActiveRecord::Base
  belongs_to :user
  ...
  def author
    user.name # this can be username or what ever field in the user's table you want 
  end
end

Now in your views you can do something like this.

- songs.each do |song|
  = song.author
  %br

I hope that this helps. Happy Hacking

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.