我有3个模型
借方和贷方非常相似。字段基本相同。我正在尝试对我的模型运行查询以返回用户为 current_user 的借方和贷方的所有字段
User.left_outer_joins(:debits, :credits).where("users.id = ?", @user.id)
Run Code Online (Sandbox Code Playgroud)
正如预期的那样,从用户返回所有字段的次数与贷记和借记中的记录一样多。
User.includes(:credits, :debits).order(created_at: :asc).where("users.id = ?", @user.id)
Run Code Online (Sandbox Code Playgroud)
它运行了 3 个查询,我认为它应该在一个查询中完成。
这个问题的第二部分是。如何将记录类型添加到查询中?
因为在来自贷方的记录中会有一个额外的字段来显示贷方,借方也是如此
我已经研究了 ActiveRecordUnion gem,但我没有看到它将如何解决这里的问题
鉴于这里的哈希数组:
arr = [{:question_type=>"Fire", :total=>0.0}, {:question_type=>"Water", :total=>0.0}, {:question_type=>"Metal", :total=>0.0}, {:question_type=>"Earth", :total=>0.0}, {:question_type=>"Wood", :total=>100.0}]
Run Code Online (Sandbox Code Playgroud)
我想选择总键值最高的哈希值。所以下面的代码似乎可以完成工作
max = arr.max_by{|x| x[:total]}
puts max[:question_type]
#=> Wood
Run Code Online (Sandbox Code Playgroud)
但是,如果我有 2 个具有相同值的哈希,它将只返回第一个
arr2 = [{:question_type=>"Fire", :total=>0.0}, {:question_type=>"Water", :total=>0.0}, {:question_type=>"Metal", :total=>0.0}, {:question_type=>"Earth", :total=>50.0}, {:question_type=>"Wood", :total=>50.0}]
max = arr2.max_by{|x| x[:total]} #it should be arr2
puts max[:question_type]
#=> Earth
Run Code Online (Sandbox Code Playgroud)
什么是得到它返回的最佳方式Earth,并Wood在情况下,两个都是最高值?
我正在尝试构建一个哈希数组,然后迭代.如果我使用下面的代码
@elements = [{:profile_id=>"123"}, {:profile_id=>"456"}]
@categories = Array.new
@elements.each do |element|
category = Category.find_by_profile_id(element[:profile_id])
@categories.push(category)
end
Run Code Online (Sandbox Code Playgroud)
它将找到最后一个对象,它将添加到数组中.但是,我想获取具有该ID的所有记录.
我一直在尝试下面的代码
@elements = [{:profile_id=>"123"}, {:profile_id=>"456"}]
@categories = Array.new
@elements.each do |element|
category = RootCategory.where(profile_id: element[:profile_id])
@categories.push(category)
end
#response
[#<ActiveRecord::Relation [#<Category id: "123", ...">, #<Category id: "123", ..."> #<ActiveRecord::Relation [#<Category id: "456", ...">, #<Category id: "456", ...">]>]
Run Code Online (Sandbox Code Playgroud)
我不能遍历返回的数组.如果我试试
@categories.each do |t|
puts t.name
end
#Prints
#Category
#Category
Run Code Online (Sandbox Code Playgroud)