Here's the relevant code.
This is a custom method I'm using.
/app/controllers/prep_sheets_controller.rb
def create_back_right
@back_sheet = PrepSheet.new().new_back_right
puts '-----------------------------------------'
puts @back_sheet
puts "this is the back sheet id below"
puts @back_sheet[:id]
if @back_sheet
render json: @back_sheet
# normally I have a render :show template, but it fails because the id returns as null.
else
render plain: "nope"
end
end
/app/models/prep_sheet.rb
class PrepSheet < ApplicationRecord
def new_back_right
self.assign_time_and_date
self.category = 'Back Fridge'
self.subcategory = 'Right'
self.save!
items = self.create_prep_items_back_right
create_relations(self, items)
self.save!
puts self[:id]
return self
end
def create_prep_items_back_right
items = PrepItem.create!([
... #it's just Item Objects, this part is fine.
])
return items
end
/config/routes.rb
Rails.application.routes.draw do
scope :api, defaults: { format: :json } do
...
post 'back_bar_prep_sheets/new_right' => 'prep_sheets#create_back_right'
...
end
end
The terminal when I run the method: Terminal Screenshot
The Postman response: Postman Screenshot
I was troubleshooting why my React frontend wasn't recieving the Prep Sheet Object normally, but it turned up as null because the :id attribute was null. So I isolated the problem and saw it was a backend problem, occurring when I render @back_sheet to json.
I'm able to recall its id fine before hand, as seen in the terminal, and it shows up in my database with its id. However, no matter if I try rendering it to json manually using 'render json' or using a template, its id doesn't seem to show up. The object itself is saved once it has been created, and saved once item relations are created.
Any idea as to why the id won't persist to json?
Oh jeez, I fixed it. Turns out (not sure exactly why) it was the attr_reader for the id in the
prep_sheet.rbmodel that was bugging it out. Once it was deleted, it was smooth sailing. Thank you all for your time and effort!I had my suspicions reading this link on github: https://github.com/rails/rails/issues/48242