RoR creating a form and passing back a hash - ruby-on-rails

thanks in advance for looking at my issue. I'm new to programming and struggling with the concept of saving data to "foreign tables".
So this is a basic survey. I have a list of questions, that have answers belonging to it.
Here is my code that iterates through all the questions and answers:
<% #questions.each do |question| %>
<ul><%= question.questiondescription %></ul>
<% #answers = question.answers %>
<% #answers.each do |answer| %>
<li><%= answer.answerdescription %></li>
<% end %>
<% end %>
This works great. However I want all the answers to be radio buttons and store the selections in another table. I have another controller and table called "assessment_results". It looks like this:
User_Id, Assessment_Id, Question_ID, Answer_Id
I need to create a new record in this table for each question and answer. How would I go about doing this with having all the questions listed on one page?
So my thinking is I need a hash to push into that table for every question.
{[user_id:1, assessment_id:, question_id:1, answer_id:3]}

You could use the radio_button_tag and parse the results yourself.
Here is the breakdown
Looking at your assessment_results table I assume you have an Assessment controller based on the 'assessment_id' column.
Lets use that to present the questions.
Here is the assessments/new.html.erb
<h1>New assessment</h1>
<%= form_for(#assessment) do |f| %>
<% if #assessment.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#assessment.errors.count, "error") %> prohibited this assessment from being saved:</h2>
<ul>
<% #assessment.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<% #questions.each do |question| %>
<%= question.questiondescription %>
<ul>
<% #answers = question.answers %>
<% #answers.each do |answer| %>
<li><%= answer.answerdescription %><%= radio_button_tag("questions[#{question.id}]", answer.id) %></li>
<% end %>
</ul>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
So we have a standard assessment form that really just gives us the form structure and assessment button, we aren't going to actually use anything from it.
Best to build the view and then look at the source code in a browser.
The work is being done by the radio_button_tag, the first value "questions[#{question.id}]"
Will produce radio buttons with a name of "questions[1]" for the first group of questions and the value will be the answer id.
When rails sees a parameter like questions[1], it will put this into a hash called questions.
Here is the raw hash from the log when submitting the form with answers filled out:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"lwqT5y+xUaYvt/GBObpN+BBO3F4YO8XaEGWcpS84lVw=", "questions"=>{"1"=>"2", "2"=>"8", "3"=>"13", "4"=>"18", "5"=>"23"}, "commit"=>"Create Assessment"}
The questions hash is:
"questions"=>{"1"=>"2", "2"=>"8", "3"=>"13", "4"=>"18", "5"=>"23"}
Now in the assessments controller, for the create method, I did the following:
def create
#assessment = Assessment.new(user_id: current_user.id)
respond_to do |format|
if #assessment.save
params[:questions].each do |question, answer|
AssessmentResult.create(user_id: current_user.id, assessment_id: #assessment.id,
question_id: question, answer_id: answer)
end
format.html { redirect_to #assessment, notice: 'Assessment was successfully created.' }
format.json { render :show, status: :created, location: #assessment }
else
format.html { render :new }
format.json { render json: #assessment.errors, status: :unprocessable_entity }
end
end
end
First we are creating an assessment that belongs to the user, I am assuming that you are using Devise or a similar system that uses the current_user for the current logged in user.
Next after saving with #assessment.save, this gives us our #assessment.id that the assessment results will belong to.
So the core work is happening here:
params[:questions].each do |question, answer|
AssessmentResult.create(user_id: current_user.id, assessment_id: #assessment.id
question_id: question, answer_id: answer)
end
end
params[:questions] - this is the params question hash that was submitted by the form.
params[:questions].each do |question, answer| - this takes the hash and for each, entry splits it into the key and value with |key, value|, in this case the key was the question id and the value was the chosen answer id.
Now we store the answer in the AssessmentResult model/table with the create command.
Say you now want to display the results of the assessment with: /assessments/1/show
def show
#assessment_results = AssessmentResult.where(assessment_id: #assessment.id)
end
Now you have the question and selected answer in the AssessmentResult
Make sure you set up your relations in the model:
app/models/assessment_result.rb
class AssessmentResult < ActiveRecord::Base
belongs_to :question
belongs_to :answer
end
Simple display of quesiton and selected answer, you will have to add the 'correct answer' code yourself.
app/views/assessments/show.html.erb
<% #assessment_results.each do |ar| %>
<%= ar.question.questiondescription %>: <%= ar.answer.answerdescription %>
<br />
<% end %>

Ok, when you have a nested models, here's what you can do
<%= form_for(#question) do |f| %>
<%= f.fields_for :answer do |ff| %>
<%= ff.label :image, 'Tag:' %>
<%= ff.checkbox :description, multiple: true, name: "answer[description]" %>
In your case, you have several answers belonging to some question, the principle is the same except you have to build specific ids for each answer, so I strongly suggest you these very helpful railscast
http://railscasts.com/episodes/197-nested-model-form-part-2
http://railscasts.com/episodes/75-complex-forms-part-3

Related

Rails doesn't send object as a param error

I've got a controller that handles articles, and recently implemented the edit and create action that way:
def edit
#article = Article.find(params[:id])
end
def update
#article = Article.find(params[:id])
if #article.update(article_params)
redirect_to #article
else
render :edit, status: :unprocessable_entity
end
end
The error occours when I try to edit an article showing the message: screenshot
I'm using a form partial to load the layout this way:
<%= render "form", article: #article %>
After trying to save an new article the edit action works properly and the body error message doesn't shows if trying to save without the requirements. What should I do so solve this problem?
Thanks in advance.
There is a better way altogether to handle rendering errors - just access the object wrapped by the form builder:
<%= form_with(model: article) do |form| %>
<% if form.object.errors.any? %>
<ul>
<% form.object.each do |error| %>
<li><%= error.full_message %></li>
<% end %>
</ul>
<% end %>
# ...
<% end %>
This lets you DRY out the rendering of errors messages without having to know the name of variable which corresponds to the model instance wrapped by the form.
However you also have a classic nil error - #article is most likely nil. And this isn't an issue we can actually help you with since it cannot be reproduced if we take the code in the question at face value. Like often with stackoverflow the actual problem it lurking somewhere outside of picture.
The debug this code you need to ensure that the code you think is running is actually running and set a series of breakpoints to verify that it is indeed being set and is being passed correctly all the way to the view.
I see that you change article to #article in edit.html.erb. Because article does not exist. article exists when you render "form", article: #article use in _form.html.erb
<% #article.erors.full_messages_for(:title).each do |message|
<div><%= message %></div>
<% end %>
But i think you don't show errors in edit.html.erb
In edit.html.erb file
<%= render "form", article: #article %>
In _form.html.erb
<%= form_with(model: article) do |form| %>
<% if article.errors.any? %>
<ul>
<% article.errors.each do |error| %>
<li><%= error.full_message %></li>
<% end %>
</ul>
<% end %>
<div>
<%= form.label :title, class: "form-control" %>
<%= form.text_field :title %>
</div>
<div>
<%= form.submit, class: "btn btn-primary" %>
</div>
<% end %>
P/S: That's my opinion, if anyone has any ideas, please leave a comment. I thank you very much

Handling radio buttons when applying to a nested form created dynamically

I have an app where users can create their own forms and then apply them to their own clients
The forms are created dynamically, meaning users can add as many questions they want, and each question has many choices (think of a survey structure).
So far so good, now I'm struggling when applying the forms, specifically getting the answers saved, persisted and showing properly when rendering the edit view.
When rendering the edit view, each question has their choices multiplied by how many questions/answers the answered_form has (I don't know exactly which of them, I am guessing here).
Answers are persisted to database, although each question has their choices multiplied, the selected answer is checked and is checked in the collection of the original answer. (answer one checked in the first 3 choices, answer two in the second 3 choices, answer three in the third 3 choices and answer four in the forth 3 choices)
I've read 2 similar questions here in SO, RoR nested attributes produces duplicates when edit, and Nested form update action producing duplicate results, but I already have the :id in strong parameters (you can see it in the code below).
I want to make myself clear here: creating the form, with nested question and nested choices is working perfectly fine, and also editing the created form. The struggle is when USING, ANSWERING or APPLYING it in the APP.
Code:
_form.html.erb:
<%= form_for [#child, #answered_form] do |f| %>
<%= f.hidden_field :form_id %>
<%= f.hidden_field :child_id %>
<div class="answered_form">
<h1><%= #form.f_title %></h1>
<h3><%= #form.f_description %></h3>
<br>
<% questions = #form.questions %>
<% i = 1 %>
<% questions.each do |question| %>
<%= i.to_s + ". " %><%= question.q_title %>
<br />
<% choices = question.choices %>
<%= f.fields_for :answers do |a| %>
<% choices.each do |choice| %>
<%= a.radio_button :a_content, choice.c_description %>
<%= a.label :a_content, choice.c_description, :value => choice.c_description, class: 'no-margin' %>
<br />
<% end %>
<% end %>
<br />
<% i += 1 %>
<% end %>
</div>
<div class="text-center">
<%= f.submit yield(:button_text), class: "btn btn-primary btn-lg" %>
</div>
<% end %>
answered_forms_controller.rb:
class AnsweredFormsController < ApplicationController
before_action :correct_answered_form, only: [:edit, :update, :destroy]
def new
#child = current_user.children.find(params[:child_id])
#form = current_user.forms.find(params[:form_id])
#answered_form = #child.answered_forms.new(form_id: params[:form_id])
#answered_form.answers.build
end
def create
#answered_form = AnsweredForm.create(answered_form_params)
if #answered_form.save
flash[:success] = "New survey " + #answered_form.form.f_title + " applied to patient!"
redirect_to current_user.children.find(params[:child_id])
else
render 'new'
end
end
def edit
#child = current_user.children.find(params[:child_id])
#form = current_user.forms.find(params[:form_id])
end
def update
if #answered_form.update_attributes(answered_form_params)
flash[:success] = "Survey updated!"
redirect_to #answered_form.child
else
render 'edit'
end
end
def show
end
def destroy
#child = current_user.children.find(params[:child_id])
#form = current_user.forms.find(params[:form_id])
#answered_form.destroy
redirect_to :back
end
private
# Strong params for creating and updating forms
def answered_form_params
params.require(:answered_form).permit(:form_id, :child_id, answers_attributes: [:id, :a_content, :a_boolean, :_destroy, :choice_id])
end
# Confirms the correct answered_form
def correct_answered_form
#answered_form = AnsweredForm.find(params[:id])
end
end
Logs:
POST:
Started POST "/children/1-juan-gomez-pereira/answered_forms" for ::1 at 2016-07-08 11:55:01 -0400
Processing by AnsweredFormsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"hFrRfEwVG4XSkdbPwrohm1QEQ0FtE/as3sM2Fj3Av3reVHJxZBVKPeuAeD713H7gVyZn7eppnULDhLJQz+EBeg==", "answered_form"=>{"form_id"=>"1", "child_id"=>"1", "answers_attributes"=>{"0"=>{"a_content"=>"Bajo"}, "1"=>{"a_content"=>"Sí"}, "2"=>{"a_content"=>"Derecha"}, "3"=>{"a_content"=>"Pesado"}}}, "commit"=>"Aplicar", "child_id"=>"1-juan-gomez-pereira"}
PATCH:
Started PATCH "/children/1-juan-gomez-pereira/answered_forms/3" for ::1 at 2016-07-08 11:55:54 -0400
Processing by AnsweredFormsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"oGdqgUR95HMkMff40Gq1zWar/CH64F0jsN3oRHT1q/H6acmMbH21yx0gWQnnDOq2ZYnYjX2aNs2tmmwChtQV8Q==", "answered_form"=>{"form_id"=>"1", "child_id"=>"1", "answers_attributes"=>{"0"=>{"a_content"=>"Bajo", "id"=>"9"}, "1"=>{"a_content"=>"Bajo", "id"=>"10"}, "2"=>{"a_content"=>"Bajo", "id"=>"11"}, "3"=>{"a_content"=>"Confuso", "id"=>"12"}, "4"=>{"a_content"=>"No", "id"=>"9"}, "5"=>{"a_content"=>"Sí", "id"=>"10"}, "6"=>{"a_content"=>"Confuso", "id"=>"11"}, "7"=>{"a_content"=>"Confuso", "id"=>"12"}, "8"=>{"a_content"=>"Confuso", "id"=>"9"}, "9"=>{"a_content"=>"Izquierda", "id"=>"10"}, "10"=>{"a_content"=>"Confuso", "id"=>"11"}, "11"=>{"a_content"=>"Izquierda", "id"=>"12"}, "12"=>{"a_content"=>"Liviano", "id"=>"9"}, "13"=>{"a_content"=>"Liviano", "id"=>"10"}, "14"=>{"a_content"=>"Pesado", "id"=>"11"}, "15"=>{"a_content"=>"Liviano", "id"=>"12"}}}, "commit"=>"Actualizar", "child_id"=>"1-juan-gomez-pereira", "id"=>"3"}
I noticed that when POST, the id for answer is not passed as a parameter. If I check the console, I can see that answer was created properly.
I think this line could be the problem
<% choices.each do |choice| %>
If you have built question.answers, you can iterate on them only using f.fields_for :answers and skip the above line. I assume choices are not much different from answers.
Please clear me if i am wrong.
So the problem was in this line of the code:
<%= f.fields_for :answers do |a| %>
fields_for helper generates fields for the entire collection of the object for whom your are calling it.
In this case, #answered_form had 4 answers after creating it, so when calling fields_for in edit, it was generating 4 fields set for each question.
To solve this, you need to specify a collection that fits your needs and pass it through the fields_for helper:
<%= f.fields_for :answers, ANSWERS_COLLECTION do |a| %>

Helper Method detect post - comment from user

I'm trying to create a helper method that will display {user.name} has no submitted posts." on the profile show view of user if they haven't yet submitted any posts and display the number posts they have . currently on my show view i have <%= render #user.posts %> which displays nothing when there are 0 posts submitted.
the partial for post is :
<div class="media">
<%= render partial: 'votes/voter', locals: { post: post } %>
<div class="media-body">
<h4 class="media-heading">
<%= link_to post.title, topic_post_path(post.topic, post) %>
<%= render partial: "labels/list", locals: { labels: post.labels } %>
</h4>
<small>
submitted <%= time_ago_in_words(post.created_at) %> ago by <%= post.user.name %> <br>
<%= post.comments.count %> Comments
</small>
</div>
</div>
ive tried :
def no_post_submitted?(user)
user.post.count(0)
"{user.name} has not submitted any posts yet."
end
on my user show view :
<%= if no_post_submitted?(#user) %>
<%= render #user.posts %>
which im more than sure is wrong but i have no idea how to implement this method .
Where you are using render #user.posts you can just add a simple conditional:
<% if #user.posts.empty? %>
<p><%= #user.name %> has no submitted posts</p>
<% else %>
<%= render #user.posts %>
<% end %>
There wouldn't be much point creating a helper for this unless you need to use it in multiple places.
Render collection returns nil if the collection is empty so you can use the || operator:
<%= render #user.posts || "{#user.name} has not submitted any posts yet." %>
Or if there is more code render another partial:
<%= render #user.posts || render 'no_posts' %>
In Ruby methods automatically return the last value so this method:
def no_post_submitted?(user)
user.post.count(0)
"{user.name} has not submitted any posts yet."
end
Will always return a string - if you use a string literal in a condition it will be evaluated as true with the warning warning: string literal in condition. Also that is not how you use count - passing 0 will cause it to query on column 0 or just error.
http://apidock.com/rails/ActiveRecord/Calculations/ClassMethods/count
So to fix the method you would do:
def no_post_submitted?(user)
user.posts.empty?
end
However that conditional is so simple that it does not really warrant a helper method. Instead you would just write:
<%= if user.post.any? %>
<%= render #user.posts %>
<% else %>
<%= "{user.name} has not submitted any posts yet." %>
<% end %>
There are a couple of problems with your solution. Remember, rails is more about convention over configuration.
Your method no_post_submitted? should actually return true/false since its a method ending with ?. Also it should be named no_posts_submitted? for clarity. It should look something like this:
def no_post_submitted?(user)
user.posts.count > 0
end
Then, there should be another helper method that will print your required message, Something like:
def no_posts_message(user)
"{user.name} has not submitted any posts yet."
end
And eventually you can all plug it in like this:
<% if no_posts_submitted?(user) %>
<%= no_posts_message(user) %>
<% else>
<%= render #user.posts %>
<% end %>
As per the docs:
In the event that the collection is empty, render will return nil, so it should be fairly simple to provide alternative content.
<h1>Products</h1>
<%= render(#products) || "There are no products available." %>
--
So...
<%= render(#user.posts) || "#{#user.name} has not submitted any posts yet." %>

How to display error messages in a multi-model form with transaction?

Two models, Organization and User, have a 1:many relationship. I have a combined signup form where an organization plus a user for that organization get signed up.
The problem I'm experiencing is: When submitting invalid information for the user, it renders the form again, as it should, but the error messages (such as "username can't be blank") for the user are not displayed. The form does work when valid information is submitted and it does display error messages for organization, just not for user.
How should I adjust the code below so that also the error messages for user get displayed?
def new
#organization = Organization.new
#user = #organization.users.build
end
def create
#organization = Organization.new(new_params.except(:users_attributes)) #Validations require the organization to be saved before user, since user requires an organization_id. That's why users_attributs are above excluded and why below it's managed in a transaction that rollbacks if either organization or user is invalid. This works as desired.
#organization.transaction do
if #organization.valid?
#organization.save
begin
# I executed next line in debugger (with invalid user info), which correctly responds with: ActiveRecord::RecordInvalid Exception: Validation failed: Email can't be blank, Email is invalid, Username can't be blank, etc.
#organization.users.create!(users_attributes)
rescue
# Should I perhaps add some line here that adds the users errors to the memory?
raise ActiveRecord::Rollback
end
end
end
if #organization.persisted?
flash[:success] = "Yeah!"
redirect_to root_url
else
#user = #organization.users.build(users_attributes) # Otherwise the filled in information for user is gone (fields for user are then empty)
render :new
end
end
The form view includes:
<%= form_for #organization, url: next_url do |f| %>
<%= render partial: 'shared/error_messages', locals: { object: f.object, nested_models: f.object.users } %>
<%= f.text_field :name %>
# Other fields
<%= f.fields_for :users do |p| %>
<%= p.email_field :email %>
# Other fields
<% end %>
<%= f.submit "Submit" %>
<% end %>
The error messages partial is as follows:
<% object.errors.full_messages.each do |msg| %>
<li><%= msg.html_safe %></li>
<% end %>
Update: Following the steps from Rob's answer I arrived at the errors partial below. This still does not display error messages for User. I added debugger responses inside the code below and for some reason nested_model.errors.any? returns false, while the debugger inside the controller (see above) does return error messages for user.
<% if object.errors.any? %>
<div id="error_explanation">
<div class="alert alert-danger">
The form contains <%= pluralize(object.errors.count, "error") %>.
</div>
<ul>
<% object.errors.full_messages.each do |msg| %>
<li><%= msg.html_safe %></li>
<% end %>
</ul>
</div>
<% end %>
<% if defined?(nested_models) && nested_models.any? %>
# Debugger: responds with "local-variable" for "defined?(nested_models)" and for "nested_models.any?" returns true.
<div id="error_explanation">
<ul>
<% nested_models.each do |nested_model| %>
# Debugger: "nested_model" has the same values as "nested_models.any?", as you would expect. But for "nested_model.errors.any?" it returns false, which it shouldn't.
<% if nested_model.errors.any? %> #Initially had "unless nested_model.valid?" but then errors for User are immediately displayed on loading the form page (new method).
<ul>
<% nested_model.errors.full_messages.each do |msg| %>
<li><%= msg.html_safe %></li>
<% end %>
</ul>
<% end %>
<% end %>
</ul>
</div>
<% end %>
Try adding validates_associated :users under your has_many :users association in Organization.
http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates_associated
Did you code successfully create a person during the rescue block?
rescue ActiveRecord::RecordInvalid => exception
# do something with exception here
raise ActiveRecord::Rollback
#organization.users.build if #organization.users.blank?
render :new and return
This code looks like it will create a new empty User regardless of incorrect validations. And render new will simply return no errors because the user was successfully created, assuming Organization has no Users.
The control flow of this method has a few outcomes, definitely needs to be broken down some more. I would use byebug and walk through the block with an incorrect Organization, then incorrect name. Then an empty Organization with incorrect User attributes.
organization has_many :users and user belongs_to :organization
organization.rb
accepts_nested_attributes_for :users
new.html.erb
<%= form_for #organization, url: next_url do |f| %>
<%= render 'shared/error_messages', object: #organization %>
<%= f.text_field :name %>
# Other fields
<%= f.fields_for(:users,#organization.users.build) do |p| %>
<%= p.email_field :email %>
# Other fields
<% end %>
<%= f.submit "Submit" %>
<% end %>
In controller
def create
#organization = Organization.new(new_params)
if #organization.save
flash[:success] = "Yeah!"
redirect_to root_url
else
render :new
end
end
This is very related to this question. The key is that <%= render 'shared/error_messages', object: f.object %> is, I assume, only calling the .errors method on the object it is passed (in this case, organization).
However, because the user errors reside with the user object, they won't be returned and therefore will not be displayed. This requires simply changing the view logic to also display the results of .errors on the various user models. How you want to do so is up to you. In the linked thread, the accepted answer had the error message display code inline instead of in a partial, so you could do it that way, but it would be somewhat redundant.
I would modify my shared/error_messages.html.erb file to check for another passed local called something like nested_models. Then it would use that to search the associated models and include the errors on that. We just would need to check whether it is defined first so that your other views that don't have a nested model won't cause it to raise an error.
shared/error_messages.html.erb
<% if object.errors.any? %>
<div class="error-messages">
Object Errors:
<ul>
<% object.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% if defined?(nested_models) && nested_models.any? %>
Nested Model(s) Errors:
<ul>
<% nested_models.each do |nested_model| %>
<% unless nested_model.valid? %>
<li>
<ul>
<% nested_model.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</li>
<% end %>
<% end %>
</ul>
<% end %>
</div>
<% end %>
Then you would just need to change a single line in your view:
<%= render partial: 'shared/error_messages', locals: { object: #organization, nested_models: #organization.users } %>
Looks like you have a lot of untestable logic in your controller. Looks like for you logic will be better to use simple FormObject pattern.
https://robots.thoughtbot.com/activemodel-form-objects

Creating multiple objects in a form Rails

So I have an interesting problem I'm working on. I am trying to create multiple objects of the same model in one view. I would like to display all the possible objects in my view, check boxes to select which ones to create, then submit and create all the corresponding objects.
Now the objects to select are gotten using an API request and returned in JSON format. The JSON is then displayed on the view for the user to select, then an array containing all the selected objects is sent back to the controller for creation.
Here is the relevant code that I've tried so far.
objects_controller.rb
def new
#possible_objects = <api call to get objs>
#objects = []
end
def create
params[:objects].each do |obj|
# create and save obj
end
end
objects/new.html.erb
<% form_for #objects do |f| %>
<% #possible_objects.each do |api_obj| %>
<%= check_box_tag(api_obj["name"])%>
<%= api_obj["name"] %>
<% end %>
<%= f.submit %>
<% end %>
This is definitely not the right approach, as the form will not accept an empty array as a parameter. I'm not sure where else to go with this, any pointers in the right direction would be great. Thanks.
Thanks to MrYoshiji for pointing me in the right direction, this is what ended up working
objects_controller.rb
def
#possible_objects = <api call to get objs>
end
def create
params[:objects].each do |object|
new_obj = Object_Model.new( <params> )
new_obj.save
if !new_obj.save
redirect_to <path>, alert: new_obj.errors.full_messages and return
end
end
redirect_to <path>, notice: 'Successfully created.'
end
objects/new.html.erb
<%= form_tag objects_path(method: :post) do %>
<% #possible_objects.each do |api_obj| %>
<%= check_box_tag 'objects[]', api_obj %>
<%= possible_object["name"] %>
<% end %>
<%= submit_tag 'Create'%>
<% end %>
Can you try the following?
# view
<% form_tag my_objects_path(method: :post) do |f| %>
<% #possible_objects.each do |api_obj| %>
<%= check_box_tag 'objects[names][]', api_obj["name"] %>
<%= api_obj["name"] %>
<% end %>
<%= f.submit %>
<% end %>
# controller
def create
params[:objects][:names].each do |obj_name|
YourModelForObject.create(name: obj_name)
end
end
See this comment on the documentation of check_box_tag: http://apidock.com/rails/ActionView/Helpers/FormTagHelper/check_box_tag#64-Pass-id-collections-with-check-box-tags

Resources