![](/img/trans.png)
[英]Rails “undefined method for ActiveRecord_Associations_CollectionProxy”
[英]Rails, The way for ActiveRecord_Associations_CollectionProxy to call method of ActiveRecord
Board&BoardThread模型
class Board < ActiveRecord::Base
has_many :board_threads
end
class BoardThread < ActiveRecord::Base
belongs_to :board
has_many :likes, as: :likable
def select_with_likes
select("*, (SELECT COUNT(likes.id) FROM likes WHERE likable_id = board_threads.id AND likable_type = 'BoardThread') AS likes_cnt")
end
end
我想使用ActiveRecord_Associations_CollectionProxy类中的“ select_with_likes”,如下所示。
b = Board.first
b.board_threads.select_with_likes.order()...
有什么好方法可以解决此问题?
您可以将逻辑移至scope
class BoardThread < ActiveRecord::Base
belongs_to :board
has_many :likes, as: :likable
scope :with_likes, -> {
select("*, (SELECT COUNT(likes.id) FROM likes WHERE likable_id = board_threads.id AND likable_type = 'BoardThread') AS likes_cnt")
}
end
board_threads = Board.first.board_threads.with_likes.order(...)
对代码稍作更改就是将self关键字添加到您的方法中,如下所示:
def self.select_with_likes
select("*, (SELECT COUNT(likes.id) FROM likes WHERE likable_id = board_threads.id AND likable_type = 'BoardThread') AS likes_cnt")
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.