Can I access the identifier of the parent object inside named_scope when retrieving related objects using the others method?

Let's say you have two models: articlesand comments.

class Article < ActiveRecord::Base
  has_many :comments
end

You know that you can get related comments on this article:

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

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

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

id named_scope. , article_id ... lambda { |article| ...} id "... #{article.id} ...", - article_id, others, has_many.

+3
4

, - : http://guides.rubyonrails.org/association_basics.html#association-extensions

, proxy_owner, @article

:

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

@article.posts.sample_extension
+4

. , , :

class Article < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  def self.get_article_id
    self.new.article_id
  end
end

@article = Article.new
@article.posts.get_article_id

Post get_article_id , . - .

+2

@ajkochanowicz, , (Rails 3.2.x), -, , , .

0

Rails 4

Rails4 +:

class Article < ActiveRecord::Base
  has_many :comments do
    def my_named_scope
      puts "Scope Owner = #{@association.owner}"
    end
  end
end

article = @article.comments.my_named_scope

my_named_scope, @association.owner Article, .comments. , Article, , , @article.

If you do not want to use extensions and rather avoid the "create a new object and get the identifier from there" method (as described in Chanpory's answer), here's how to do it:

class Article < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  def self.get_article_id
    Comment.scope_attributes["article_id"] # scope_attributes returns a hash of all the attributes inherited from the owner of this scope
  end
end

@article = Article.find(10)
@article.comments.get_article_id  # returns 10
0
source

Source: https://habr.com/ru/post/1730930/


All Articles