【发布时间】:2013-11-21 09:04:44
【问题描述】:
RAILS - 远程模型关联
基本上,我在使用has_many :through => 时遇到了一些困难
我有四个感兴趣的模型:
- 填字游戏
- 细胞
- 线索
- 单词
一个填字游戏有很多单元格,一个单元格有很多线索,一个线索属于一个单词
或者,视觉上:
Crossword --< Cell --< Clue >-- Word
现在我已经设置了关联,允许我在一个查询中从填字游戏到线索,但我不知道如何设置它们以让我在一个查询中从填字游戏一直到单词。
class Crossword
has_many :cells
has_many :clues, through: :cells
end
所以 Crossword.first.clues 有效!但是当我尝试以下...
class Crossword
...
has_many :words, through: :clues
end
...没有骰子。
我可以使用.map 轻松解决这个问题:
Crossword.first.clues.map{|clue| clue.word}
但我真的想弄清楚这是如何使用适当的 ActiveRecord 关联来完成的。
任何帮助将不胜感激,谢谢!
编辑:这是我的示例查询的结果:
> Crossword.first.clues
=> [<Clue id: 4, content: "ExampleABC123", word_id: 2 >]
和
> Crossword.first.clues.words
=> Crossword Load (0.6ms) SELECT "crosswords".* FROM "crosswords" ORDER BY "crosswords"."id" DESC LIMIT 1
=> Clue Load (4.3ms) SELECT "clues".* FROM "clues" INNER JOIN "cells" ON "clues"."id" = "cells"."clue_id" WHERE "cells"."crossword_id" = $1 [["crossword_id", 32]]
=> NoMethodError: undefined method `words' for #<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_Clue:0x007fd000d5e238>
【问题讨论】:
-
那么当你尝试上面的代码时你得到了什么?一些错误,空的结果?您是否尝试过在控制台中运行
crossword.words.to_sql? -
好吧,在上传我的输出之后,我终于找到了我的问题,这是一个愚蠢的问题。我没有输入
Crossword.first.words,而是输入Crossword.first.clues.words。我的联想其实很好,我就是个笨蛋。 -
我将记录我的错误并将其标记为已关闭。对不起,伙计们!
标签: ruby-on-rails activerecord rails-activerecord has-many-through model-associations