hrvladev
hrvladev

Reputation: 133

Can I write this in more idiomatic Active Record way?

How can I rewrite this piece of code to use maximum of the Active Record Query interface and minimum SQL? Is there more idiomatic way to write it?

ticket_gifts = Gift
  .joins("LEFT JOIN giftable_items ON gifts.giftable_item_id = giftable_items.id")
  .select("gifts.total_value, gifts.created_at, gifts.user_id")
  .where("giftable_items.gift_type = 'ticket'")
  .to_sql

It's doing its job, but I'm not satisfied with that how it looks.

Upvotes: 3

Views: 73

Answers (1)

MrYoshiji
MrYoshiji

Reputation: 54882

I think this should do it:

Gift.joins(:giftable_item).where(giftable_items: { gift_type: 'ticket' })

Depending on what is the relation between Gift & GiftableItem, if it is a has_many, use the pluralized version in the joins:

Gift.joins(:giftable_items).where(giftable_items: { gift_type: 'ticket' })
                         ^

Update: With a select:

Gift.joins(:giftable_items)
    .where(giftable_items: { gift_type: 'ticket' })
    .select(['total_value', 'gifts.created_at', 'user_id'])

Upvotes: 4

Related Questions