RAILS -远程模型关联
基本上,我对has_many :through =>有一些困难
我有四种感兴趣的模式:
横字词有许多细胞,细胞有许多线索,线索属于一个词
或者,视觉上:
Crossword --< Cell --< Clue >-- Word现在,我已经建立了我的关联,允许我在一个查询中从Crossword获得线索,但我不知道如何设置它们,让我从Crossword一直到一个查询中的单词。
class Crossword
has_many :cells
has_many :clues, through: :cells
end所以Crossword.first.clues起作用了!但当我尝试以下方法时..。
class Crossword
...
has_many :words, through: :clues
end...no骰子。
我可以用.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>发布于 2013-11-21 09:51:03
这里的问题不是我的协会,而是我的投入。
我的协会如下:
class Crossword < ActiveRecord::Base
...
has_many :cells
has_many :clues, through: :cells
has_many :words, through: :clues
...
end这准确地建模了我的系统,但是当我试图获取填字游戏的单词时,我继续要求example_crossword.clues.words而不是example_crossword.words。
案子结案了!
https://stackoverflow.com/questions/20116493
复制相似问题