【发布时间】:2016-01-25 16:16:42
【问题描述】:
我有 4 个表格,如下所示:
User:
-id
-name
....
UserMapLayer:
-id
-auto_refresh
....
SystemLayer:
-id
-Name
-Path
UserLayer:
-id
-Name
-Path
我想通过我的用户对象进行查询,它将为我提供以下 JSON 结构中的所有 SystemLayer 和 UserLayer 对象
[{layer_id: UserMapLayer.id, name: **THE NAME FROM SystemLayer or UserLayer**, path: **THE PATH FROM SystemLayer or UserLayer**, auto_referesh: UserMapLayer.auto_refresh, source: *'SYSTEM' or 'USER' depending on the whether the record is from SystemLayer or UserLayer*}, {....}]
如您所见,我想在 UserMapLayer 中存储一些属性,但我不想在连接表中复制名称、路径等内容。
我对 Rails 和 ActiveRecord 还很陌生,并且对如何将模型相互映射一无所知...这是我的第一次通过...
class User < ActiveRecord::Base
has_many :user_map_layers
end
class UserMapLayer < ActiveRecord::Base
belongs_to :user
belongs_to :user_layers
belongs_to :system_layers
end
class UserLayer < ActiveRecord::Base
has_many :user_map_layers
end
class SystemLayer < ActiveRecord::Base
has_may :user_map_layers
end
我收到了大量不同的错误,但基本上我什至不知道从哪里开始。我什至不知道如何用谷歌搜索来解决这类问题。我可以在直接的 SQL 联合查询中编写此查询,所以我想我正在尝试在 ActiveRecord 中复制它。
我想我正在尝试使用 ActiveRecord 执行以下 SQL 查询:
SELECT ul.name, ul.path, uml.auto_refresh from user_layers ul, user_map_layers uml where
uml.layer_id = ul.id and uml.type = 'USER' and uml.user_id = 1
UNION
SELECT sl.name, sl.path, uml.auto_refresh from system_layers sl, user_map_layers uml where
uml.layer_id = sl.id and uml.type = 'SYSTEM' and uml.user_id = 1
任何帮助将不胜感激。
【问题讨论】:
标签: ruby ruby-on-rails-4 activerecord rails-activerecord