【发布时间】:2012-05-08 13:05:37
【问题描述】:
我有两个模型:
class Sentence < ActiveRecord::Base
attr_accessible :sentence_id, :authority_name #...
end
class Rule < ActiveRecord::Base
attr_accessible :description, :headline, :note, :sentence_id
end
我想知道如何在 Rule 上创建 belongs_to :sentence 关联,其行为类似于以下伪 SQL 代码:
SELECT * FROM rules
INNER JOIN sentences ON rules.sentence_id = sentences.sentence_id;
编辑:
我想要这样的东西
rule = Rule.find 797
# we all know how SQL query will look like...
rule.sentence
# => SELECT * FROM sentences
INNER JOIN rules ON rules.sentence_id = sentences.sentence_id
WHERE rules.id = 797
【问题讨论】:
-
这里的问题是你想获取属于任何句子的所有规则(即,有些规则的 sentence_id 为空)?如果每个规则都属于一个句子,为什么句子模型的基本
has_many :rules和规则模型的belongs_to :sentence不能完成你想要的? -
向问题添加了更多信息。 :)
-
在我看来,基本的关联设置可以满足您的需求。这种方法缺少什么?
-
这种方法缺少foreign_key的设置。当你做像
belongs_to :sentence这样的基本关联时,你仍然可以通过INNER JOIN sentences ON sentences.id = rules.sentence_id加入而不是INNER JOIN sentences ON sentences.sentence_id = rules.sentence_id。我想最后一次加入。仔细读。 :P :D
标签: sql ruby-on-rails ruby-on-rails-3 associations belongs-to