我的rails应用程序中有多个模型
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
并且还有两个相机和用户模型,我正在获取具有日期SnapshotReport.find_by_report_date("01/19/2016")
的snapshot_report,但将其保存到@report
,我想在视图中显示来自用户和相机的一些数据比如
user = who is owner of the camera
exid = which is of camera
上述查询的结果是
#<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>
我的其他协会是
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"
用户
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'
答案 0 :(得分:1)
您可以通过关联获取用户和相机信息。
user = @report.camera.user
exid = @report.camera.exid