Given these models

  class Category < ActiveRecord
    has_many :category_assignments
    has_many :posts, :through => :category_assignments
  end

  class CategoryAssignment < ActiveRecord::Base
    belongs_to :post
    belongs_to :category
    # Has boolean column 'featured'
  end

  class Post < ActiveRecord::Base
    has_many :category_assignments
    has_many :categories, :through => :category_assignments
  end

I want to add a named_scope to Post that will return all featured
posts. But the semantics of this named_scope vary depending upon
whether I am calling the named scope on Post or on category.posts:
  Post.featured
is simple enough. The definition
  named_scope :featured,
              :joins => :category_assignments,
              :conditions => {:category_assignments.featured => true }
will return all posts for which any associated category_assignment
record has featured = true.

But when I take a category instance and call category.posts.featured I
want to get all of the posts which are featured *in that category*,
which requires restricting by category_id. To do this properly the
named_scope code needs to be able to determine whether it's being
called in a context in which category_assignments has already been
joined (and/or whether a category_id is specified in the conditions).
I have not figured out how to do this.

If I can detect whether or not the named_scope is being called within
the context of an association then I can do something like the
following, which changes named_scope semantics based on whether or not
a category _argument_ is explicitly provided:

  named_scope :featured, lambda { |*args|
    if (category = args.first)
      { :joins => :category_assignments,
        :conditions => {:category_id => category.id,
                        :featured    => true} }
    else
      { :joins => :category_assignments,
        :conditions => {:featured    => true} }
    end
  }

Is there some way to inspect a joins or conditions hash to determine
association state from within a named_scope? And if so, is it reliable
regardless of the order of named_scope stacking (i.e. will it work for
either category.posts.other.named.scopes.featured or
category.posts.featured.other.named.scopes)?

Thanks,

Sven
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to