通过Rails ActiveRecord Association调用Class方法

时间:2016-01-05 23:32:38

标签: 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 = 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

问题是是否有更好的方法来了解调用类方法的关联对象(post)的id。一种方式(上面使用的)是:post_id = self.new.post_id。 我打赌有一种更清洁的方式,我不必创建一个对象只是为了获得post_id

2 个答案:

答案 0 :(得分:3)

情绪分析是你的一个重要的商业逻辑,也许它会增长很多,所以我认为最好把它放在它自己的课堂上。

如果您这样做,您将能够将帖子传递给分析器(例如):

function onDeviceReady(){
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(fs) {
var directoryReader = fs.createReader();
directoryReader.readEntries(function(entries) {
var i;
for (i=0; i<entries.length; i++) {

document.addEventListener('deviceready', onDeviceReady2, false);  
function onDeviceReady2() {  
    function readFromFile(fileName) {
        var pathToFile = cordova.file.externalDataDirectory + fileName;
        window.resolveLocalFileSystemURL(pathToFile, function (fileEntry) {
            fileEntry.file(function (file) {
                var reader = new FileReader();

                reader.onloadend = function (e) {
                console.log("Inside Load" + JSON.parse(this.result));
                    return JSON.parse(this.result);
                };

                reader.readAsText(file);
            }, errorHandler.bind(null, fileName));
        }, errorHandler.bind(null, fileName));
    }


    function some_function(callback) {

    console.log("inside function1"); 
    var data = readFromFile(entries[i].name);

    callback(data);
}



some_function(function(data) {


    console.log("data!" + data);
    console.log("Data String!" +  JSON.stringify(data));

});


  //  var obj = JSON.parse(data);
  // console.log("arresteeFirst!" + data.arresteeFirst);
   // console.log("data!" + data);
}
console.log(entries[i].name);
}


}, function (error) {
alert(error.code);
});
}, function (error) {
alert(error.code);
});
}

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

# 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

答案 1 :(得分:3)

直接回答你的问题,

Comment.scope_attributes

将返回Comment的当前范围将设置的那些属性的哈希值。您可以像这样测试关联对此的影响

我不确定我是否会使用它 - 拥有一个只能在特定表单的作用域上调用的类方法似乎有点奇怪。