tags:

views:

80

answers:

1

Quite possibly there could be a rails magic I've missed, but I'm guessing it will be in Ruby.

I have a model called Company which has_many Contacts.

Suppose Company has Contact 1, Contact 2, Contact 3, and Contact 4.

When I create a textblog for each Contact, I want to output the following (where Contact = Contact 1)

"Hi, Contact 1, I am also writing to Contact 2, Contact 3, and Contact 4."

So it needs to extract the Contact in the salutation and then list them, inserting "and" before the last Contact in the list.

Edit

I now have the following:

This is in contacts_controller.rb

  def full_name
   [self.first_name, self.last_name].compact.join(" ")
  end

in contact_letters_controllers.rb (contact_letters are the executed contacts with letters)

  def new

    @contact_letter = ContactLetter.new
    @contact_letter.contact_id = params[:contact]
    @contact_letter.letter_id = params[:letter]

    @contact = Contact.find(params[:contact])
    @company = Company.find(@contact.company_id)

    contacts = @company.contacts.collect(&:full_name)

    contacts.each do |contact|
       @colleagues = contacts.reject{ |c| [email protected]_name }
    end

    @letter = Letter.find(@contact_letter.letter_id)

    @letter.body.gsub!("{FirstName}", @contact.first_name)
    @letter.body.gsub!("{Company}", @contact.company_name) 
    @letter.body.gsub!("{Colleagues}", @colleagues.to_sentence)

    @contact_letter.body = @letter.body
    @contact_letter.status = "sent"

  end 
+3  A: 

I believe to_sentence is what you're looking for.

You could try something like the following:

contacts = Company.contacts.collect(&:name)

contacts.each do |contact|
   other_contacts = contacts.reject{ |c| c==contact }
   p "Hi, #{contact}, I am also writing to #{other_contacts.to_sentence}"
end

I didn't test this code, so forgive me if this doesn't work.

Edit

This method will return the contact's full_name. If you also have a middle_name attribute, you can add on the array. This method will still work if any of the attributes is nil.

def full_name
   [self.first_name, self.last_name].compact.join(" ")
end
j.
pretty close...one challenge. The contacts have a :first_name and :last_name, how can I aggregate these into a single :full_name?
Angela
other than that, I've got something working, thanks!
Angela
you can add a `full_name` method to your `Contact` model. see my edited answer...
j.
Hi, thanks --- so where would I put the method? I've edited to show what I've done...thanks. This change creates an undefined method:undefined method `full_name'
Angela
You must put the method on `Contact` model.
j.
ah yep, got it it works -- virtual attribute....cool bnz, thanks!
Angela