PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 21, 2022

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

 October 21, 2022     has-many, ruby-on-rails     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing