Ruby on Rails Polymorphic - Controller and View Solution

I've been trying to silence my polymorphic structure for my application for a while, but I can't get it, and I don't know how to solve it.

I have a Vendor model and the vendor profile can be a company OR the person listed below.

Supplier model

class Supplier < ActiveRecord::Base
    belongs_to :profile, :polymorphic => true
    accepts_nested_attributes_for :personable, :allow_destroy => true, :reject_if => :all_blank
end

      

Company model

class Company < ActiveRecord::Base
    has_one :supplier, as: :profile
end

      

Character model

class Person < ActiveRecord::Base
    has_one :supplier, as: :profile
end

      

At the model level (in the console) my associations work fine, but I have to use the ones between the two previous versions of the model ( supplier.profile = Company.new

for example).

What I want is, when the user goes to the NEW Supplier action, they can select in the form if the Supplier is a Person or Company, and then something needs to be done to show the correct fields. And go back to the Create action, handle everything.

I read a lot of questions on stackoverflow and looked at Ryan Bates' roles # 197 and # 394.

I am a Rails enthusiast, not a programmer.

If anyone can point me in the right direction, I would be grateful.

Regards, David

+3


source to share


1 answer


It depends a lot on the variety of fields you need and how much data is being used. But if they are very different from each other, I actually have two separate sections or sections on the page, which radio buttons toggle showing one and hide the other using javascript. This can be done quite easily with jquery at the bottom of the view, given its default in rails:

 <input type="radio" name="supplier_type" value="person" />
 <input type="radio" name="supplier_type" value="company" />

 <script>
   $('input[name="supplier_type"]').on('change', function () {
      if ($(this).val() === "person") {
        $('.person-form').show();
        $('.company-form').hide();
      }
      else {
        $('.person-form').hide();
        $('.company-form').show();
      }
   });
 </script>

      

Then inside each of these divs there is a completely separate form that posts different actions. If the data is different enough to require two forms, it is worth having two different controllers for that.



Now if it's just a few fields of fields, or an extra field for one, or something else. I would have a radio button similar to the one above in form_for. Add javascript again to show or hide values. In the controller, use check for switch value to get the parameters you need:

 supplier_params = params.slice :list, :of, :generic, :params

 if params[:supplier_type] == "company"
   supplier_params.merge! params.slice :company_name
 elsif params[:supplier_type] == "person"
   supplier_params.merge! params.slice :person_name
 end

 Supplier.new supplier_params 

      

+1


source







All Articles