Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 %>
like image 407
Anthony To Avatar asked Aug 15 '26 05:08

Anthony To


1 Answers

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

like image 149
MrYoshiji Avatar answered Aug 16 '26 19:08

MrYoshiji



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!