Search code examples
ruby-on-railsrubyruby-on-rails-4activerecordmodels

Rails: Select from multiple models


In my rails application i a have a job model

belongs_to :company
belongs_to :organization

and i want to drop-down a name list of all company name and organization name in the same field so I'm wondering if this is possible actually I was just using company name before i have added the organization, I have this code in my job form

<%= f.text_field :company_name, data: {autocomplete_source: Company.order(:name).map(&:name) },required: true %>    

and this in my job model

def company_name
  company.try(:name)
end

def company_name=(name)
   self.company = Company.where(name: name).first_or_create
end

Solution

  • I don't really understand the difference between Company and Organization. I'm assuming Company and Organization have no relation to each other. So you can just union the two sets.

    <% companies_and_organizations = (Company.all.pluck(:name) + Organization.all.pluck(:name)).sort %>
    <%= f.text_field :company_name, data: {autocomplete_source: companies_and_organizations}, required: true %>
    

    Then I assume you only assign one or the other field. In this case creating a Company if the selected name does not match an existing Company or Organization:

    def company_name
      (company || organization).try(:name)
    end
    
    def company_name=(name)
       company_or_organization = Organization.where(name: name).first
       company_or_organization ||= Company.where(name: name).first_or_create
       self.company = company_or_organization
    end