Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 通过Rails ActiveRecord关联调用类方法_Ruby On Rails_Ruby_Activerecord_Associations - Fatal编程技术网

Ruby on rails 通过Rails ActiveRecord关联调用类方法

Ruby on rails 通过Rails ActiveRecord关联调用类方法,ruby-on-rails,ruby,activerecord,associations,Ruby On Rails,Ruby,Activerecord,Associations,我有两门课: class Post < ActiveRecord::Base has_many :comments end class Comment < ActiveRecord::Base belongs_to :post # Class method # does some analysis on all the comments of a given post def self.do_sentiment_analysis post_id

我有两门课:

class Post < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :post

  # Class method
  # does some analysis on all the comments of a given post  
  def self.do_sentiment_analysis
     post_id = self.new.post_id  # Is there a better way to get post_id?

     # real code that does something follows

  end

end


# Class method is called on a post object like this:
Post.find(1).comments.do_sentiment_analysis
class Post
问题是是否有更好的方法来知道调用类方法的关联对象(post)的id。一种方法(上面使用)是:
post\u id=self.new.post\u id

我打赌有一种更干净的方法,我不必创建一个对象来获取
post\u id

情绪分析是您的一个重要业务逻辑,也许它会增长很多,所以我认为最好将它放在自己的类中

如果这样做,您将能够向分析器传递post(例如):

现在您可以重写您的示例:

# app/models/analyzer.rb
class Analyzer
  def initialize(post)
    @post = post
  end

  def sentiment
    @post.comments.each do |comment|
      do_something_with comment
      # ... more real stuff here
    end
  end

  def some_other_analysis
  end

  private
  def do_something_with(comment)
    # ...
  end
end
Analyzer.new(Post.find(1)).sentiment

直接回答你的问题,

Comment.scope_attributes
将返回注释上当前作用域将设置的那些属性的散列。您可以这样测试关联对此的影响


但我不确定我是否会使用它——有一个只能在特定形式的作用域上调用的类方法似乎有点奇怪。

在我看来,这是一个很好的方法,因为它将向未来的您(编写代码的人)以及偶然发现代码的可能的代码维护者显示“正确”放置分析逻辑的位置。我并不是反对在活动记录模型上添加一些逻辑(在本例中是注释),我只是建议这是一种特定的逻辑,可以从适当的增长点中受益。除了
post_ID=self.new.post_ID
,还有什么方法可以获取关联对象的ID吗?这只是一个示例代码。真正的代码不做任何情绪分析。对一篇文章的所有评论都进行了一个非常小的处理,因此不能保证创建一个新类。同样,我们甚至不需要post ID来迭代注释。这个问题是为了好奇,当以这种方式调用静态方法时,我们如何获得关联对象的id?这正是我想要的答案。替换
post\u id=self.new.post\u id
,如您所建议的那样:
post\u id=Comment.scope\u属性[“post\u id”]
。至于我为什么要这么做,如果你想对一篇文章的所有评论进行一些处理,并且想调用
post.find(1.comments.process\u comments
,它可能会很有用。这个
过程\u comments
可以是
Comment
的类方法。虽然没有必要,但我可能想知道哪个“所有者”称这个协会——这就是问题所在。