Ruby 如何使用联接表中的属性在ActiveRecord中创建关系

Ruby 如何使用联接表中的属性在ActiveRecord中创建关系,ruby,ruby-on-rails-4,activerecord,rails-activerecord,Ruby,Ruby On Rails 4,Activerecord,Rails Activerecord,我有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

我有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

任何帮助都将不胜感激

欢迎来到Rails!当你不知道该怎么称呼你正在寻找的东西时,制定一个搜索查询是很困难的


您正在使用ActiveRecord关联,因此您需要完全熟悉该指南,以及顶部导航栏中“指南索引”弹出窗口中提供的相关指南。尽可能多地坚持官方来源,因为多年来模型定义和关联在提高安全性方面已经有了很大的发展,所以旧的教程、示例甚至书籍都会告诉您过去是如何实现的,但在今天的控制器操作中可能会导致无声故障。这些指南真的是一个很好的方法,可以让您了解发展真正成熟的应用程序所需的基本知识。

谢谢您的链接。。。这是好东西。我从医生那里学到了很多!我的问题仍然是,“我想做的事情是现实的吗?”是的!关键在于让一个模型的id在相关表中表示为main_model_id,因为ActiveRecord会创建必要的访问器方法。一定要了解:has_many:through模型,因为这样做所有简单的关联都更有意义。当您超越了ActiveRecord关联的内置功能时,也要知道您可以在模型上创建自己的方法,以执行任何其他需要的操作。例如,我经常在我的模型文件中创建两个方法,一个叫“about”,另一个叫“description”“about”是一个类方法,它在我离开项目几个月后提醒我这个模型是关于什么的,它的缺点是什么,等等。“description”通常是我正在查看的唱片集的控制台报告。非常好的建议。。。我现在正在开发一个示例应用程序,看看我是否掌握了要点!完成后我会更新!再次感谢!
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