【发布时间】:2016-04-09 22:55:44
【问题描述】:
我有两个类:
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 而创建对象。
【问题讨论】:
标签: ruby-on-rails ruby activerecord associations