In my app:
A song has many setlists through allocations
A setlist has many songs through allocations
allocations belong to setlists and songs
I’m trying to add a song from the existing library to a set list using the following form:
<% @songs.each do |song| %>
<tr>
<%= nested_form_for(@setlist.allocations.build(song_id: song.id)) do |f| %>
<td><%= song.title %></td>
<td><%= song.artist %></td>
<td><%= song.key %></td>
<td>
<div><%= f.hidden_field :song_id %></div>
<%= f.submit "ADD", class: "btn btn-small btn-primary" %>
<% end %>
</td>
</tr>
<% end %>
In my setlists controller I have:
def edit
@songs = Song.all(order: 'title')
@setlist = Setlist.find(params[:id])
@setSongs = @setlist.songs
@allocations = Allocation.where("setlist_id =?", @setlist)
end
def update
@setlist = Setlist.find(params[:id])
song = Song.find(params[:song_id])
@setlist.allocate!(song)
if @setlist.update_attributes(params[:setlist])
# Handle a successful update.
flash[:success] = "SAVED!"
redirect_to setlists_path
else
render 'edit'
end
end
The allocate method is specified in the setlist model as:
def allocate!(song)
allocations.create!(song_id: song.id)
end
At the moment it returns the following whenever I click to add songs to the setlist.
NoMethodError in SetlistsController#update
undefined method `id’ for :song:Symbol
The bug is also wierd in that it only does the error above for the first record in the table, whilst all the others render the “error” page for when a record hasn’t been added.
Any pointers would be appreciated. Thanks very much in advance
You are passing the Symbol
:songtoallocate!inwhen
allocate!is expecting an instance ofSongto be passed. The:songsymbol has no method.id, hence the error.If you’re trying to pass the
Songrelated toyou must first get the
Song.