ctilley79 ctilley79 - 6 months ago 18
Ruby Question

Rails Conditional Select Contents

I'm populating a select tag dynamically within my form. The select tag is populated by a query to

Payee
. I have a couple fields I'd like to display as the text value of the element. However it must be done conditionally. For example.

fields:

:company
:first_name
:last_name


I can concatenate those three in the text box like so:

f.select :payee_id, Payee.all.collect { |p| [p.company.to_s + " " + p.first_name.to_s + " " + p.last_name.to_s, p.id] }


The above doesn't work the way I desire. If
company
exists, I would like to leave out
first_name
and
last_name
.

if
company
is blank, I'd like to display only
first_name
and
last_name


currently if
company
and
first_name
exist it concatenates the two together, which I do not desire.

I know how to query the database for each case separately, but I don't know how to combine the results so the select tag will display correctly.

Here's what I have of my helper so far. I know it's currently a mess, but I need help understanding the method to get this done.

def expense_payee_id_field(f)
@payee_with_company = Payee.where("company IS NOT NULL and company !='' ")
@payee_without_company = Payee.where("(first_name != '' or last_name != '') and company = '' ")

f.select :payee_id, Payee.all.collect { |p| [p.company.to_s + " " + p.first_name.to_s + " " + p.last_name.to_s, p.id] }
end

Answer

You should just create a method in your Payee model that does this logic for you:

# Payee.rb

# I've extracted this into its own method
# because you very well may need it later
def full_name
  [first_name, last_name].join(" ")
end

# This can be written more concisely, but I've
# kept it as-is to allow for better readability
def display_name
  if company_name.blank?
    full_name
  else
    company_name
  end
end

Now, you can simply call payee.display_name and it will print the desired result.

Comments