1

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.

2 Answers 2

1

First. Your has_many association named as :tracks, but in form and strong params you have :record_tracks so you cannot create them via this form. You have to use same name as association in forms and strong params.

Second. You call @record.tracks.build in create action which will build new empty Track object, and then save on Record will save it along with parent Record object. Don't call @record.tracks.build in create action - it expects a new data to be passed from a form, not created new blank.

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

Comments

0

You'll need to pass the :name in the correct params hash:

#app/controllers/records_controller.rb
class RecordsController < ApplicationController
   def record_params
      params.require(:record).permit(:name, :artist_id, tracks_attributes: [:name])
   end
end

1 Comment

Thanks for your help! Between yours and Oleg's answers, I was able to get this working

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.