aRtoo
aRtoo

Reputation: 1892

How to construct form_for in Rails that can create both belongs_to and has_many association

I have a has_many and belongs_to association in my Rails app. An OfficeAddress belongs_to Address, so my problem right now is how to build it on the form. When I create a new office address, to associate it into my address, the address should be created already. On my office_address_controller I have this.

class OfficeAddressesController < ResourceController
      def index
        @office_address = Spree::OfficeAddress.all
      end

      def new
        new_address = Spree::Address.new
        @new_office_address = new_address.office_address.build
      end

      def create
        p params
      end

    end

and on my office address new.html.erb is currently empty because I can't find any documentation on how to build a form. I'd be interested in examples or documentation. Also the controller build confuses me. It didn't throw any error I was expecting error as new_address doesn't have any Id yet.

Upvotes: 0

Views: 59

Answers (1)

aRtoo
aRtoo

Reputation: 1892

So I don't know if this is the right answer but this works for me. So here's my code.

Controller:

def new
     @new_office_address = Spree::OfficeAddress.new
    end

def create
     b = Spree::Address.create(permit_params_address)
     c = Spree::OfficeAddress.create(address_id: b.id)
     if b.save && c.save
        redirect_to admin_office_addresses_path
     else
        p b.errors.messages
     end
end

View, new.html.erb

<%= form_for [:admin, @new_office_address], html: { autocomplete: "off" } do |ofc_add_form| %>
          <fieldset data-hook="new_property">
            <div class="row">
              <div class="col-md-12">
                <%= fields_for :address, Spree::Address.default  do |adds|%>
                  <%= render :partial => 'spree/admin/shared/address_form', :locals => { :f => adds, :type => "New Office Address" } %>
                <%end%>
              </div>
            </div>

            <div class="form-actions">
              <%= render partial: 'spree/admin/shared/new_resource_links' %>
            </div>
          </fieldset>
        <% end %>

I was doing the right thing at first but I forgot to Spree::Address.default on fields_for I don't really know what it does but on the rails syntax, it accepts an object.

on my controller new method, after creating the address, to relate them with each other (OfficeAdddress) I just grab the Id from the address that was created and add it on my office address. I'm not sure this is the best way to solve the problem. I'm open for changes. I'm also adding more validation on my new method

Upvotes: 0

Related Questions