Joins parent and child tables in rails


1. Get parent objects:



Alert.joins("LEFT JOIN alert_events on alert_events.alert_id = alerts.id 

").group('alerts.id').select('alerts.*')


2. Get Child Object:


AlertEvent.joins("INNER JOIN alerts on alerts.id = alert_events.alert_id 
").group('alert_events.id').select('alert_events.*')

Active record for child object
AlertEvent.joins(:alert).where(alerts: {category: 'Pay'})



3. Joins multiple tables:



 @previous_seafood_items = SeafoodItem.joins("LEFT JOIN auction_items on auction_items.itemable_id = seafood_items.id and auction_items.itemable_type = 'SeafoodItem' and auction_items.auction_id is NULL")
    .group('seafood_items.id')
    .select('seafood_items.*')
    .where(user_id: current_user.id )

    .paginate(:page => params[:page], :per_page => 20)

Comments

Popular Posts

How to pass hash in Postman

nginx: unrecognized service

Bootstrap Select Picker append add new item if search not exist

Reading Excel Sheets using "Roo" gem in ruby on rails

Add CORS to Nginx on AWS Elastic Beanstalk

Enable gzip compression on Elastic Beanstalk with nginx

Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'

Get video duration by URL in Ruby on Rails

site-enables nginx setting in ruby in rails