TheGreatDeVane TheGreatDeVane - 5 months ago 15
Ruby Question

Rails 4 nested form data not being saved, has many through association

I'm trying to make an app that allows people to submit info to one model, while also filling in some data about it from another model. Currently the form works, but the data for the nested form isn't saving

Here's my controller


class Requests::AgesController < ApplicationController
def new
@age = Age.new
@industries = Industry.all.map{ |i| [i.name, i.id ]}
@age.ages_industries.build
end

def create
@age = Age.new(age_params)

if @age.save
flash[:success] = "Age #{@age.name} has been created!"
redirect_to admin_ages_path
else
flash.now[:error] = "Sorry! We were unable to create that age."
render "new"
end
end

private

def age_params
params.require(:age)\
.permit(:name,
:about_title,
:about_body,
:url,
:email,
:phone,
:street,
:city,
:state,
:zip,
:country,
:is_published,
age_industries_attributes: [:age_id, :industry_id])
end
end


relevant bits of the age model

has_many :ages_industries,
dependent: :delete_all
accepts_nested_attributes_for :ages_industries


has_many :industries,
:through => :ages_industries,
:uniq => true


ages_industries model

class AgesIndustry < ActiveRecord::Base
belongs_to :age, touch: true
belongs_to :industry
accepts_nested_attributes_for :industry
self.primary_key = :id
end


relevant bits of the industry model

has_many :ages_industries
has_many :ages,
:through => :ages_industries,
:uniq => true


form

section#main
.wrapper
h1 Add an Age
= simple_form_for [:requests, @age] do |form|
.formElem.m20t.m20b
= form.error_notification
.formElem.m20b
= form.input :name
.formElem.m20b
= form.simple_fields_for :ages_industries do |builder|
= builder.input :industry_id, collection: @industries, :value => params[:id]
.fix
.formElem.m20b
= form.input :about_title
.formElem.m20b
= form.input :about_body
.formElem.m20b
= form.input :url
.formElem.m20b
= form.input :email
.formElem.m20b
= form.input :phone
.formElem.m20b
= form.input :street
.formElem.m20b
= form.input :city
.formElem.m20b
= form.input :state
.formElem.m20b
= form.input :zip
.formElem.m20b.m20t
= form.input :country, collection: Carmen::country_names
.fix
.formElem.m20b
= form.input :is_published
.formElem.m20b.m20t
= form.button :submit, class: "formBtn"
| or
= link_to "cancel", admin_ages_path


If someone could point me in the right direction, it would be greatly appreciated.

Answer

At the very least, you're missing a pluralization when you permit the nested params. i.e. ages instead of age.

params.require(:age).permit(ages_industries_attributes: [...])

If that doesn't fix it, I would put a pry or a byebug in your controller create action and check out the contents of params and age_params to make sure they are aligned.