Nick Roberts
Nick Roberts

Reputation: 11

belongs_to Name attribute not saving in nested rails form

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.

Upvotes: 1

Views: 305

Answers (2)

Richard Peck
Richard Peck

Reputation: 76774

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

Upvotes: 0

Oleg Antonyan
Oleg Antonyan

Reputation: 3113

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.

Upvotes: 1

Related Questions