I have two models: I have a nested form that allows users to enter attributes for @contact and @goal. However, when I go to save the form input, I get the following error:
1 error prohibited this contact from being saved:
Goals contact can't be blank
Here are my goal and contact models, along with the contact controller:
class Contact < ActiveRecord::Base
belongs_to :user
has_many :goals
accepts_nested_attributes_for :goals, allow_destroy: true
validates_presence_of :user_id,:name,:title,:email
end
class Goal < ActiveRecord::Base
belongs_to :contact
validates_presence_of :title, :due_date, :contact_id
end
class ContactsController < ApplicationController
before_action :set_contact, only: [:show, :edit, :update, :destroy]
# GET /contacts
# GET /contacts.json
def index
@contacts = current_user.contacts
end
# GET /contacts/1
# GET /contacts/1.json
def show
end
# GET /contacts/new
def new
@contact = Contact.new
1.times { @contact.goals.build }
end
# GET /contacts/1/edit
def edit
end
# POST /contacts
# POST /contacts.json
def create
@contact = Contact.new(contact_params.merge(user_id: current_user.id))
respond_to do |format|
if @contact.save
format.html { redirect_to @contact, notice: 'Contact was successfully created.' }
format.json { render :show, status: :created, location: @contact }
else
format.html { render :new }
format.json { render json: @contact.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /contacts/1
# PATCH/PUT /contacts/1.json
def update
respond_to do |format|
if @contact.update(contact_params)
format.html { redirect_to @contact, notice: 'Contact was successfully updated.' }
format.json { render :show, status: :ok, location: @contact }
else
format.html { render :edit }
format.json { render json: @contact.errors, status: :unprocessable_entity }
end
end
end
# DELETE /contacts/1
# DELETE /contacts/1.json
def destroy
@contact.destroy
respond_to do |format|
format.html { redirect_to contacts_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_contact
@contact = Contact.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def contact_params
params.require(:contact).permit(:name, :title, :company, :email, :notes, goals_attributes: [:title, :due_date, :notes, :contact_id])
end
end
I made sure to add goals_attributes to the contact params (in Contacts Controller). Any thoughts on what the issue may be? Here's a link to the project: https://github.com/nowgeez/radiusapp
Thanks!