简体   繁体   中英

rails associations to retrieve record

I have multiple models in my rails application

class SnapshotReport < ActiveRecord::Base
  establish_connection "evercam_db_#{Rails.env}".to_sym

  belongs_to :camera

  def self.add_report
    camera_report = Snapshot.connection.select_all("select camera_id,count(*) as snapshot_count from snapshots where created_at in (select created_at from snapshots where created_at >= 'now'::date - 1 and  created_at >= 'now'::date - 1) group by camera_id").to_hash

    camera_report.each do |camera|
        SnapshotReport.create(camera_id: camera["camera_id"], snapshot_count: camera["snapshot_count"], report_date: Date.yesterday)
    end
  end
end

and there are two camera and user model as well, i am getting snapshot_report with date as SnapshotReport.find_by_report_date("01/19/2016") but saving this to @report , i want to show on view some data from user and camera as well such as

user = who is owner of the camera
exid = which is of camera

result of the above query is

#<SnapshotReport id: 40, camera_id: 5992, created_at: "2016-01-20 08:25:11", report_date: "2016-01-19 00:00:00", snapshot_count: 345>

my other associations are

class Camera < ActiveRecord::Base
  establish_connection "evercam_db_#{Rails.env}".to_sym

  belongs_to :user, :foreign_key => 'owner_id', :class_name => 'EvercamUser'
  belongs_to :vendor_model, :foreign_key => 'model_id', :class_name => 'VendorModel'
  has_many :camera_shares, dependent: :delete_all
  has_many :snapshot_report, foreign_key: "camera_id", class_name: "SnapshotReport"

user

class EvercamUser < ActiveRecord::Base
  establish_connection "evercam_db_#{Rails.env}".to_sym

  self.table_name = "users"
  belongs_to :country
  has_many :cameras, :foreign_key => 'owner_id', :class_name => 'Camera'
  has_many :snapshots
  has_many :vendors
  has_many :camera_shares, :foreign_key => 'user_id', :class_name => 'CameraShare'

You can just get the user and camera information through the associations.

user = @report.camera.user
exid = @report.camera.exid

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM