Friday, October 21, 2022

[FIXED] How to get first and second records from a table having has_many relation in Rails?

Issue

I am having a relation where contacts :has_many emails and email :belongs_to contacts. my contacts.xls.erb file:

class ContactsXLS < BaseXLS
  def add_content
   contacts.each do |contact|
    write_array [contact.title,
    contact.updated_at,
    contact.email,
    contact.phone,
    first_email(contact),
    second_email(contact) ]
   end
  end

  def first_email(contact)
    contact.emails.each do |emm|
    emmm.first.email
    end
  end
  def second_email(contact)
    contact.emails.each do |emm|
    emmm.last.email
    end
  end

end

I have to add email fields from emails table which belongs for a particular contact in above file. Here the relation between 2 tables is: emailable_id in emails table = id in contacts table.

I tried in console as :

c =Contact.find('1wqwqwqw212121')
c.emails.first.email #ex@ex.com

I think we need to write a method and call this array but I couldn't. My requirement is to print first record and second record, please help.


Solution

As per the relation contacts :has_many emails, we can write in array as:

contact.emails.first.try(:email) 

likewise for displaying the first record.



Answered By - venkat
Answer Checked By - David Goodson (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.