我有以下两个子查询:
@sub= ShareDetail.where(:dump_date_id=>2,:file_from_id=>1).select('TotalShares AS previous').group('previous')
@sub1= ShareDetail.where(:dump_date_id=>1,:file_from_id=>1).select('TotalShares AS current').group('current')
在模型中:
class ShareHolder < ActiveRecord::Base
has_many :share_details,:dependent=>:destroy
end
我想在
中使用这些子查询 @shareHolders= ShareHolder.where(:client_id=>session[:shareinvestor_user_id]).......
我不知道如何使用这些子查询。请帮帮我。
最佳答案
你试过了吗scopes ?
class ShareHolder < ActiveRecord::Base
has_many :share_details,:dependent=>:destroy
scope :sub, -> { where(:dump_date_id=>2,:file_from_id=>1).select('TotalShares AS previous').group('previous') }
scope :sub1, -> { where(:dump_date_id=>1,:file_from_id=>1).select('TotalShares AS current').group('current') }
end
然后你可以使用这个:
@shareHolders= ShareHolder.where(:client_id=>session[:shareinvestor_user_id]).sub
更新
class ShareHolder < ActiveRecord::Base
has_many :share_details,:dependent=>:destroy
end
class ShareDetail < ActiveRecord::Base
scope :sub, -> { where(:dump_date_id=>2,:file_from_id=>1).select('TotalShares AS previous').group('previous') }
scope :sub1, -> { where(:dump_date_id=>1,:file_from_id=>1).select('TotalShares AS current').group('current') }
end
还有这个:
@shareDetails= ShareHolder.find_by(client_id: session[:shareinvestor_user_id]).share_details.sub
关于mysql - 在 Rails 4 中使用子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31913715/