Reputation: 11
Do you know because a parent field could not be part of the insert statement even though there is parent-association defined in the model classes?
Basically, i want to save the creator logged into the application in a document submission table when it save its questions. By the way, questions are saved properly. Here is my database model
Also, below is the classes I created and modified
JSON which is sent from the browser
Parameters: {"submission"=>{"responses_attributes"=>{"0"=> {"question_id"=>"71", "answer"=>"Answer 1-10"},
"1"=>{"question_id"=>"72", "answer"=>"Answer 1-10"}}}, "document_id"=>"1"}
Document submissions controller
class DocumentSubmissionsController < ApplicationController
def index
@document = Document.find_by_slug(params[:document_id])
@submissions = @document.submissions.includes(:responses)
end
def create
document = Document.find_by_slug(params[:document_id])
if document.submissions.create(submission_params)
render json: document, status: 200
else
render status: 400
end
end
private
def submission_params
params.require(:submission).permit(
submission: [admin_id: 1],
responses_attributes: [
:question,
:answer_value
]
)
end
end
Submission and response model classes
class Submission < ActiveRecord::Base
# Associations
belongs_to :document, inverse_of: :submissions
has_many :responses, class_name: "SubmissionResponse", inverse_of: :submission, dependent: :destroy
belongs_to :creator
# Nested Attributes
accepts_nested_attributes_for :responses
end
class Creator < ActiveRecord::Base
has_many :submissions
end
Insert statement got from Rails track
(0.4ms) BEGIN
SQL (4.3ms) INSERT INTO "document_submissions" ("document_id", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"
[["document_id", 1], ["created_at", "2016-06-12 21:07:57.481249"], ["updated_at", "2016-06-12 21:07:57.481249"]]
... response inserts....
(0.9ms) COMMIT
Thanks,
Upvotes: 0
Views: 58
Reputation: 3275
I think you can just do
if document.submissions.create(submission_params) && document.update_attributes(creator_id: current_user.id)
render json: document, status: 200
else
render status: 400
end
Upvotes: 0