[英]Rails, The way for ActiveRecord_Associations_CollectionProxy to call method of ActiveRecord
Board & BoardThread model 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
And I want to use 'select_with_likes' from ActiveRecord_Associations_CollectionProxy class like below. 我想使用ActiveRecord_Associations_CollectionProxy类中的“ select_with_likes”,如下所示。
b = Board.first
b.board_threads.select_with_likes.order()...
What is awesome way to work this? 有什么好方法可以解决此问题?
You can move the logic into a scope
您可以将逻辑移至
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(...)
Slight change to the code is to add the self keyword to your method like so: 对代码稍作更改就是将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.