Ruby on rails 3 rails3和正确使用关联的方法

Ruby on rails 3 rails3和正确使用关联的方法,ruby-on-rails-3,model-associations,Ruby On Rails 3,Model Associations,我正在做我的第一个rails3应用程序 联想没有意义。首先,即使是导轨也不会 真正解释他们做什么,他们只是解释如何使用它们。 据我所知,协会做了两件事: a) Allow ActiveRecord to optimize the structure of the database. b) Allow ActiveRecord to offer an alternate ruby syntax for joins and the like (SQL queries).

我正在做我的第一个rails3应用程序

联想没有意义。首先,即使是导轨也不会 真正解释他们做什么,他们只是解释如何使用它们。 据我所知,协会做了两件事:

    a) Allow ActiveRecord to optimize the structure of the database.
    b) Allow ActiveRecord to offer an alternate ruby syntax for
       joins and the like (SQL queries). I want this.
我试图理解关联,以及如何正确使用它们。基于 在下面的例子中,关联似乎是“断裂的”,或者至少是断裂的 文件是

考虑一下我的应用程序的一个简单版本。修改词表的老师 为了学习

本次讨论共有3个相关表格。为了清楚起见,我只是 包括注释1工具的表定义,并已删除 不必要的字段/列

单词列表管理表:

    Table name: wordlist_mgmnt_records
    id         :integer         not null, primary key
    byline_id  :integer(8)      not null
将单词映射到单词列表的表格:

    Table name: wordlists
    wordlist_mgmnt_id :integer         not null
    word_id           :integer         not null
实际上,我们并不在乎这些词本身。但我们确实关心 最后一张表,署名:

    Table name: bylines
    id           :integer(8)      not null, primary key
    teacher_id   :integer         not null
    comment      :text            not null
署名记录谁、使用了什么工具、地点、时间等。署名是 主要用于故障排除,以便我可以向用户解释发生了什么 他们应该做和/或修复他们的错误

教师可以一次修改一个或多个单词表管理记录 又名单署名。换句话说,一次更改可能会更新多次 单词表

对于单词表管理记录,关联为:

    has_many :bylines       # the same byline id can exist
                            # in many wordlist_mgmnt_records
但是署名对应的条目是什么

Rails 3 Carneiro等人的书开头写道:

    "Note: For has_one and has_many associations, adding a belongs_to
    on the other side of the association is always recommended. The
    rule of thumb is that the belongs_to declaration always goes in
    the class with the foreign key."
[是的,我也看过在线rails指南,没有吗 帮助。]

对于署名表/类,我真的想说什么

    belongs_to :wordlist_mgmnt_records
那真的没有道理。署名表基本上属于 数据库中的每个表都有一个署名id。我真的会这么说吗 你属于他们所有人吗?这不会在所有的数据库中设置外键吗 其他桌子?这反过来又会使改变变得更昂贵 CPU周期比我想要的多。一些变化影响了很多表格,一些 它们非常大。我重视正常使用的速度,并愿意等待 使用署名进行清理/修复时,查找没有外键的署名

这给我们带来了一个完整的循环。协会在rails中真正做的是什么, 人们如何明智地使用它们

仅仅使用关联,因为你可以,似乎不是正确的
回答,但是您如何获得添加的连接语法呢?

我将尝试帮助您解决困惑

一个署名可以有多个单词列表记录,因此定义其中的has\u many似乎是有意义的

我不确定我是否理解你在另一方面的困惑。由于您已经定义了属性wordlist\u mgmnt\u records.byline\u id,因此任何给定的wordlist\u mgmnt\u记录只能“have”属于一个署名行。如果您喜欢数据库图,只需通过ruby定义crows foot:

wordlist_msgmnt_records (many)>>----------(one) byline
或者用英语阅读:一个署名可以有多个单词列表,而许多单独的单词列表可以属于一个署名

将“属于”定义添加到wordlist\u mgmnt模型不会影响查询的性能,只需执行以下操作:

@record = WordlistMgmntRecord.find(8)
@record_byline = @record.byline
此外,您还可以在表上执行联接,如:

@records = WordlistMgmntRecord.joins(:byline).where({:byline => {:teacher_id => current_user.id}})
它将执行以下SQL:

SELECT wordlist_mgmnt_records.*
FROM wordlist_mgmnt_records
INNER JOIN bylines
  ON wordlist_mgmnt_records.byline_id = bylines.id
WHERE bylines.teacher_id = 25
假设当前_user.id返回25

这是基于您当前的数据库设计。如果您发现有一种方法可以实现您想要的功能,而无需在wordlist\u mgmnt\u records表中将byline\u id作为外键,那么您可以修改您的模型以适应它。然而,这似乎是一个规范化数据库的外观,我不确定还有什么其他方法可以做到这一点