How to add a column of another model to a specific model



  • LikeSQLUseCompanyHome belongs_toHome BalanceModelBackwardationI get the same date and time of the model together.

    sql =<<-SQL
     SELECT balances.*, backwardations.rate
     FROM balances LEFT JOIN backwardations
       ON balances.date = backwardations.date AND balances.company_id = backwardations.company_id
     WHERE balances.company_id = #{company_id}
    SQL
    ActiveRecord::Base.connection.select_all(sql).to_hash
    

    If possibleHashnotBalancemodel pseudobackwardation_rateI want to get with the column added.
    ASIs it possible to use such as:

    Balance.selectSorry, this entry is only available in 日本語.FROM "balances"It was impossible because it came to the end.

    BalanceHomeBackwardationHomecompany_idHomedateColumnuniqueRestrictions
    DBPostgresqlUse



  • ASto useActiveRecord::Base.connection.select_allnotModel.find_by_sqlThe column of another model can be obtained by alias.

    sql =<<-SQL
     SELECT balances.*, backwardations.rate AS backwardations_rate
     FROM balances LEFT JOIN backwardations
       ON balances.date = backwardations.date AND balances.company_id = backwardations.company_id
     WHERE balances.company_id = #{company_id}
    SQL
    balance = Balance.find_by_sql(sql)
    

    balance.backwardations_rate #=> 0.5


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2