Sylar
Sylar

Reputation: 12092

How to add conditions for json model association

Im trying to include an association but only ones based on its attribute's value

Joo Model:

def as_json(options = {})
  super(include: [:foo, (:bar).where('bar.accepted = ?', true)])
end

undefined method `where' for :bar:Symbol

Doing super(include: [:foo, :bar]), I have no control of what I want. How to accomplish what Im trying to do? Only include where bar.accepted == true

I was looking at this to see if it was possible. Im using Rails 5 API.

Edited to show associations:

Joo:

has_many  :bars, dependent: :destroy
belongs_to :foo

Foo:

has_many  :bars, dependent: :destroy

Bar:

belongs_to  :foo
belongs_to  :joo

Upvotes: 1

Views: 336

Answers (1)

Pavan
Pavan

Reputation: 33542

As per the doc I see there isn't way to include associations conditionally. I think you can make a conditional association on model Joo and call it in as_json

Class Joo < ApplicationRecord
  belongs_to :foo
  has_many :bars, dependent: :destroy
  has_many :accepted_bars, -> { where accepted: true }, class_name: "Bar"
end

Then you call it like

@joo = Joo.all.reverse
@joo.as_json(include: [:foo, :accepted_bars])

Note: Not tested!

Upvotes: 1

Related Questions