views:

135

answers:

1

Let's say you have two models: articles and comments.

class Article < ActiveRecord::Base
  has_many :comments
end

You know you can fetch associated comments to an article like this:

article = Article.first
article.comments # => SELECT * FROM "comments" WHERE ("comments".article_id = 123)

Is there a way to explicitly access the article_id (123) within a named_scope?

I need this for a complex named_scope that joins another table. Basically the named_scope will depend on to be called from the associated parent object to make sense (article.comments.my_named_scope and not Comments.my_named_scope).

I don't want to pass the id as a parameter for the named_scope. So, instead of passing the article_id to the named scope with ... lambda { |article| ...} and access the id with "... #{article.id} ...", I want to somehow access this article_id that the others method uses, which I get from the has_many association.

+1  A: 

Sounds like what you're actually after is an association extension: http://guides.rubyonrails.org/association_basics.html#association-extensions

In particular, proxy_owner, which will be the @article in question

eg:

class Article < ActiveRecord::Base
  has_many :posts do
    def sample_extension
      puts "Proxy Owner #{proxy_owner}"
    end
  end
end

@article.posts.sample_extension
Mark Connell
Originally, I wanted to access the parent's object id for use in a JOIN statement of my named_scope. This doesn't seem to be possible. But it **is** possible when I use an association extension and use the `proxy_owner` variable.So, this is not exactly how I would like to have it worked, but still good. Thanks for your answer, Mark.
Daniel Pietzsch