blueprinter icon indicating copy to clipboard operation
blueprinter copied to clipboard

association scope

Open Talha5 opened this issue 4 years ago • 1 comments

consider these models:

class Theme < ApplicationRecord
  # Relationships
  has_many :templates
end
class Template < ApplicationRecord
  # Relationships
  belongs_to :theme

  # Enums
  enum status: { active: 0, inactive: 1 }
end

and its blueprinter:

class ThemeBlueprinter < ApplicationBlueprinter
  fields :id, :page
  
  association :templates, blueprint: TemplateBlueprinter < -- how to define association scope here?
end

using blueprinter as:

ThemeBlueprinter.render_as_hash(@theme)

I'd like to call template scope active when its querying for templates association to get only active templates. is it possible?

Talha5 avatar Aug 16 '21 19:08 Talha5

I think you can try to do it within a block:

class ThemeBlueprinter < ApplicationBlueprinter
  fields :id, :page
  
  association :templates, blueprint: TemplateBlueprinter do |theme|
  	theme.templates.active
  end
end

However you can also define scoped association active_templates, which probably would be better, since query would be performed outside of the view logic.

sl4vr avatar Aug 31 '21 20:08 sl4vr

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

github-actions[bot] avatar Nov 01 '23 01:11 github-actions[bot]