Question

I am rying to add a subsidiary to a company. SO I will go the company, and the select from a list 1 or more subsidiaries and save. So I am NOT saving a company to a subsidiary (as it seems its the case below), but rather adding a subsidiary to the company,

So then this example below makes no sence to me! I mean how do I save the subsidiary to a company?

class Company < ActiveRecord::Base
    validates   :name, presence: true
    has_many :subsidiaries, :class_name => "Company", :foreign_key => "parent_company_id"
    belongs_to :parent_company, :class_name => "Company",
end 

Could you please show me how the save would look in my controller, as Im sure this is where Im going wrong.

Current my problem is that the way I save Im saving the supposed to be subsidiary as the parent_id, so basicly its reversed:

here I select a subsidiary from a list:

<%= f.collection_select(:parent_company_id, @companies, :id, :name, :include_blank => true, :multiple => true) %>

Just to be clear what currently happens:

  1. I open company A
  2. I select company B as a subsidiary and save
  3. I look at companies and see that B has a subsidiary A (wrong!!) and it makes sense because its parent_id was set to A, but actually I need to set its "subsidiary_id"
Was it helpful?

Solution

The typical way of doing this:

<p>Parent Company</p>
<%= f.collection_select :parent_company_id, ... %>

You go around to all the child company records and set their parent company. Afterwards, you take a look at @parent.subsidiaries for your list.

If you want to do this all from the parent company's form, you'll have to do some trickery with javascript and fields_for and accepts_nested_attributes_for, or maybe with a bunch of checkboxes -- the record that is actually changed is the child record, not the parent record.

Watching this railscast may help.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top