I am having a tough time figuring out how to make a form_object that creates multiple associated objects for a has_many
association with the virtus gem.
The problem is that the format of the JSON being passed to UserForm.new()
is not what is expected.
The JSON that you are passing to it, in the user_form_params
variable, currently has this format:
{
"name":"testform",
"emails":{
"0":{
"email_text":"email1@test.com"
},
"1":{
"email_text":"email2@test.com"
},
"2":{
"email_text":"email3@test.com"
}
}
}
UserForm.new()
is actually expecting the data in this format:
{
"name":"testform",
"emails":[
{"email_text":"email1@test.com"},
{"email_text":"email2@test.com"},
{"email_text":"email3@test.com"}
}
}
You need to change the format of the JSON, before passing it to UserForm.new()
. If you change your create
method to the following, you won't see that error anymore.
def create
emails = []
user_form_params[:emails].each_with_index do |email, i|
emails.push({"email_text": email[1][:email_text]})
end
@user_form = UserForm.new(name: user_form_params[:name], emails: emails)
if @user_form.save
redirect_to @user, notice: 'User was successfully created.'
else
render :new
end
end