简体   繁体   中英

Rails 4 Passing in dynamic named scopes on polymorphic models

I have a polymorphic model called Assignment that belongs to both Task and Item through owner_type, owner_id.

Task & Item have scopes called :upcoming and :today and :this_month. I am trying to use ONE named scope on assignments to get all the data I need...but it's not quite working.

In this example, "timeline" coule equal "today", "this_month" or "upcoming"

The query would be

Assignment.by_timeline("task", "this_month")

here is my named scope on Assignment (Task.this_month works on it's own):

     scope :by_timeline, lambda { |owner_type, timeline|
        owner = owner_type.to_sym
        owner_class = owner_type.camelize.constantize
        set_scope = timeline.to_sym
        scoped_owner = owner_class.timeline

        joins(owner).merge(scoped_owner)
  }

It works when I replace "owner_class.timeline " "with owner_class.this_month", but I want to set the named scope on the owner_type dynamically.

I ended up doing this:

scoped_owner = owner_class.send("#{timeline}")

I used the send

ALL THE CREDIT GOES TO THIS QUESTION

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM