ruby on rails - Filtering polymorphic association by type for a view -


i have polymorphic association looks this:

class event < activerecord::base   belongs_to :eventable, :polymorphic => true end 

with bunch of types:

class nap < activerecord::base   include eventable end  class meal < activerecord::base   include eventable end  module eventable   def self.included(base)     base.class_eval       has_one :event, :as => :eventable, :dependent => :destroy       accepts_nested_attributes_for :event, :allow_destroy => true        scope :happened_at, -> (date) {         where("events.happened_at >= ? , events.happened_at <= ?",         date.beginning_of_day, date.end_of_day).order("events.happened_at asc")       }        base.extend(classmethods)     end   end    module classmethods     define_method(:today)       self.happened_at(date.today)     end   end end 

and on.

here's other end of relationship:

class person < activerecord::base   has_many :events    has_many :meals, {     :through => :events,     :source => :eventable,     :source_type => "meal"   }   has_many :naps, {     :through => :events,     :source => :eventable,     :source_type => "nap"   }   has_many :moods, {     :through => :events,     :source => :eventable,     :source_type => "mood"   }   has_many :notes, {     :through => :events,     :source => :eventable,     :source_type => "note"   }   ... end 

i want grab events of types belong person display in single view. here's i'm doing:

def show   @events = event.by_person(@person).happened_at(date)    @meals, @naps, @moods, @notes = [], [], [], [], []   @events.each |e|     @meals << e.eventable if e.eventable_type == 'meal'     @naps << e.eventable if e.eventable_type == 'nap'     @moods << e.eventable if e.eventable_type == 'mood'     @notes << e.eventable if e.eventable_type == 'note'   end end 

i need filter type because view going displaying type-specific attributes in each section of view.

question: should logic of filtering out collection of events type own type-specific arrays exist in controller? or elsewhere? perhaps model?

i reluctant pass @events view , have type test happen in view itself. seemed wrong.

you can use @events query create subquery without having iterate (i'm assuming have inverse has_many :events, as: :eventable in each of other models):

@events = event.by_person(@person).happened_at(date)  @meals = meal.joins(:event).where events: { id: @events } @naps  =  nap.joins(:event).where events: { id: @events }  # etc. 

Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -