I'm new do rails and MVC. I'm trying to save to my database a nested form that I made using simple-form and nested-form-for gems. When I submit the form only the 'parent' model is created and saved. Thankyou very much.
'parent model':
class Diet < ApplicationRecord
belongs_to :coach
has_many :user_eat_diets
has_many :user, through: :user_eat_diets
accepts_nested_attributes_for :user_eat_diets
has_many :diet_composes
has_many :foods, through: :diet_composes
accepts_nested_attributes_for :diet_composes
end
'child' model:
class DietCompose < ApplicationRecord
belongs_to :diet
belongs_to :food
end
'parent' controller:
class DietsController < ApplicationController
def new
@diet = Diet.new
@diet.diet_composes.build
end
def create
@diet = Diet.new(diet_params)
if @diet.save
flash[:success] = "success"
end
end
def diet_params
params.require(:diet).permit(:name, :coach_id, :diet_composes_attributes)
end
end
'child' controller:
class DietComposesController < ApplicationController
def new
@diet_compose = Diet_compose.new
end
def create
@diet_compose = Diet_compose.new(diet_compose_params)
if @diet_compose.save
flash[:success] = "success"
end
end
def diet_compose_params
params.require(:diet_compose).permit(:quantity, :hour, :day, :food_id, :diet_id)
end
end
the form view:
<%= simple_form_for @diet, :html => {:class => 'form-basic' } do |f| %>
<%= f.input :name %>
<%= f.input :coach_id %>
<%= f.nested_fields_for :diet_composes do |ff| %>
<%= ff.remove_nested_fields_link %>
<%= ff.input :hour %>
<%= ff.input :day %>
<%= ff.input :food_id %>
<%= ff.input :diet_id %>
<% end %>
<%= f.add_nested_fields_link :diet_composes %>
<%= f.button :submit %>
<% end %>
Also, when I do the command
Diet_compose.all
on rails console I got the error
LoadError: Unable to autoload constant Diet_compose, expected /home/tanaka/Desktop/E-xercite/app/models/diet_compose.rb to define it from (irb):8