Making an api call that has on it a parent record (which is item) and children records (which are photos) the item record get saved fine, but the images it only save one image with missing fields.
Here is the json im sending
{"item_category": "Books & Magazines", "item_condition": "Used",
"item_name": "Crushing it", "summary": "super awesome",
"price": 20, "active": true,"instant": 1,
"access_token": "p8Z-yZ1wRooBLsZj4yeS",
"photo_attributes":
[{"created_at": "2019-05-16 05:28:16.696408",
"image_file_name": "images.jpg",
"image_content_type": "image/jpeg","image_file_size": 257908,
"image_updated_at":"2019-05-21 15:20:55.390445"},
{"created_at": "2019-05-16 05:28:16.696408",
"image_file_name": "images.jpg",
"image_content_type": "image/jpeg","image_file_size": 257908,
"image_updated_at":"2019-05-21 15:20:55.390445"}
]}
this is the api im calling
http://localhost:3000/api/v1/createitem
here is image of the command line
as you see here the item got saved
as you see here it only took one image with 3 fields
this items.contoller.rb
class Api::V1::ItemsController < ApplicationController
def createitem
@item = current_user.items.new(item_params)
if @item.save
render json: @item, status: :ok
else
render json: { error: "Something went wrong", is_success: false}, status: 422
end
end
def item_params
params.require(:item).permit(:item_category, :item_condition,:item_name,:summary,:address,:price,:active, :instant, photo_attributes:[:created_at, :image_file_size, :image_updated_at, :image_file_name, :image_content_type])
end
end
this is the item.rb model
class Item < ApplicationRecord
enum instant: {Request: 0, Instant: 1}
belongs_to :user
has_many :photos
accepts_nested_attributes_for :photos
validates :item_category, presence: true
validates :item_condition, presence: true
end
I tired this solution but still did not save any photo Rails 4 nested attributes not saving
here is the update items.controller.rb
class Api::V1::ItemsController < ApplicationController
def createitem
@item = current_user.items.build(item_params)
@item.photos.each do |photo|
photo.build
end
if @item.save
render json: @item, status: :ok
else
render json: { error: "Something went wrong", is_success: false}, status: 422
end
end
def item_params
params.require(:item).permit(:item_category, :item_condition,:item_name,:summary,:address,:price,:active, :instant, photos_attributes:[:created_at, :image_file_size, :image_updated_at, :image_file_name, :image_content_type])
end
end