0

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
1
  • Put the logic in view is bad practice. Commented Feb 2, 2015 at 4:37

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

Yes there is no relation between organization and company they are two different model. I will give your code a try but can you tell me if a record doesn't exist it will be created as a company or organization or both??
Note that I edited this (I missed || on the where checks). In the code I chose to create a Company if record doesn't exist. I don't know which you prefer to do; you can swap the Organization/Company where clauses. Just make sure you first_or_create the last one.
Also, in case you are wondering .pluck(:name) is like .map(&:name) (that you used) except that it only returns the one field from the database, rather than loading every record and instantiating an object. So a little performance improvement if you have lots of Companies or Organizations.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.