1

I am trying to setup a form that takes in some song information. Right now the song title and the song artist.

Here is some of my code so far.

Song Model *EDIT

class Song < ActiveRecord::Base

  has_one :song_artist_map
  has_one :artist, :through => :song_artist_map
  accepts_nested_attributes_for :artist

end

Artist Model

class Artist < ActiveRecord::Base
  has_many :song_artist_maps
  has_many :songs, :through => :song_artist_maps
end

SongArtistMap Model

class SongArtistMap < ActiveRecord::Base
  belongs_to :song
  belongs_to :artist
end

Songs Controller

def new 
  @song = Song.new
  @song.artist.build
end

And inside my form I added this code

<% f.fields_for :artist do |a| %>
    <li><%= a.label :name %></li>
    <li><%= a.text_field :name %></li>
<% end %>

Right now nothing shows up in my form for artists.

So I need a way to be able to add an Artist from the form when a song is add and then make the mapping or just make the mapping if the artist already exists in my database.

I know I'm doing something very wrong here, can anyone please help? Thanks!

Dan
  • 2,299
  • 2
  • 20
  • 41
  • actually with this exact code I get this error from my controller `undefined method 'build' for nil:NilClass` – Dan Mar 29 '12 at 00:40
  • I am starting to think now that I don't need a has_one through association here. I can just add a column to my song table that will map to my artists table. Is this the right direction of thinking? and if so how do I accomplish that? – Dan Mar 29 '12 at 02:15

1 Answers1

1

In your Song model, it should be has_many :artists?

If you do

"artist".pluralize
 => "artists" 

That's what Rails uses for the auto-lookups of a few things, especially with has_many relationships, so it could be the source of your problems.

EDIT

In that case, the problem is in your controller. Instead of @song.artist.build, you should have @song.build_artist.

With a has_many relationship, Rails uses an object that allows you to instantiate new ones, with a has_one, it just returns it (which can be nil.).

Joe Pym
  • 1,826
  • 12
  • 23
  • I'm sorry it was supposed to be has_one, I changed it to resemble what my code actually looks like right now. – Dan Mar 29 '12 at 00:15
  • thanks along with that my other major issue was `<% f.fields_for :artist do |a| %>` which had to be `<%= f.fields_for :artist do |a| %>` – Dan Mar 29 '12 at 13:42