I have two models that are nested, a Project has a name and a Budget, and a Budget has an amount and belongs to a Project.
I got a form page where I try to create both Project and Budget, so users can fill the name of their project in the same form where they choose the budget amount.
<%= simple_form_for @project do |f| %>
<%= f.error_notification %>
<%= simple_fields_for :budget do |ff| %>
<%= ff.input :amount %>
<% end %>
<%= f.input :name %>
<%= f.submit "Create", class: "btn" %>
<% end %>
But I can't create both at the same time, when I test if my budget is valid, I miss the project_id it is linked to, and if I try to create my project first, I can't cause it misses its budget.
Here are my models :
class Budget < ApplicationRecord
belongs_to :projects
end
class Project < ApplicationRecord
has_one :budget
accepts_nested_attributes_for :budget
end
Here are my migrations
class CreateBudgets < ActiveRecord::Migration[5.1]
def change
create_table :budgets do |t|
t.timestamps
end
end
end
class CreateProjects < ActiveRecord::Migration[5.1]
def change
create_table :projects do |t|
t.references :budget, foreign_key: true
t.string :name
t.timestamps
end
end
end
Finaly here is my controller for project def new @project = Project.new @project.id = 0 @budget = Budget.new puts "new in projectcontroler" end
def create
puts "create in projectcontroler"
# Getting filled objects from form
@project = Project.new(project_params)
@budget = Budget.new(budget_params)
puts "We're on project controller"
p @budget
respond_to do |format|
unless @budget.nil?
@project.budget = @budget
if @project.valid?
puts "All good now"
@budget.save
@project.save
puts "Campaign successfuly created"
format.html { redirect_to projects_path, notice: 'Success' }
else
puts "Unable to create campaign"
format.html { render :new, notice: 'Project went wrong' }
end
else # If budget isn't saved
puts "Unable to create budget"
@budget.errors.full_messages.each do |mes|
puts mes
end
format.html { render :new }
format.json { render json: @budget.errors, status: :unprocessable_entity }
end
end
end
For now I got this issue : ActiveModel::MissingAttributeError - can't write unknown attribute project_id
I need to understand if I need to have a controller or routes for budget model, can't I create both models in this same controller ?
EDIT : Updated code
EDIT 2 : I add migrations as I think it's part of the problem
class CreateProjects < ActiveRecord::Migration[5.1]
def change
create_table :projects do |t|
t.references :budget, foreign_key: true
t.string :name
t.timestamps
end
end
end
class CreateBudgets < ActiveRecord::Migration[5.1]
def change
create_table :budgets do |t|
t.string :amount
t.timestamps
end
end
end