I am creating a simple app to input and display albums. I can create a record (album) and assign it an artist (which are created in the artists controller). I want to add tracks to a record , and do this in one form (using simple form), using one controller (the records controller).
Here is my record model
class Record < ActiveRecord::Base
belongs_to :artist
has_many :tracks
accepts_nested_attributes_for :tracks
Here is my track model
class Track < ActiveRecord::Base
belongs_to :record
Here's the records controller
class RecordsController < ApplicationController
def index
@records = Record.all
end
def new
@record = Record.new
end
def create
@record = Record.create(record_params)
@record.tracks.build
@record.save!
redirect_to records_path
end
def record_params
params.require(:record).permit(:name, :artist_id, record_tracks_attributes: [:name])
end
and here is my records/new/html.haml page
= simple_form_for @record do |f|
= f.collection_select(:artist_id, Artist.all, :id, :name, prompt: true)
= f.input :name
= f.simple_fields_for :record_tracks do |t|
= t.input :name
= t.button :submit
= link_to 'add artist', new_artist_path
It appears to save fine, however when I look in the console, I get the following
> Track.last
Track Load (0.6ms) SELECT "tracks".* FROM "tracks" ORDER BY "tracks"."id" DESC LIMIT 1
=> #<Track id: 20, name: nil, created_at: "2015-10-05 17:30:30", updated_at: "2015-10-05 17:30:30", record_id: 39>
I can't work out why the name is not saving for the track. Where am I going wrong? Any help would be greatly appreciated.