【问题标题】:Rails: Associating Models at Long-RangeRails:远程关联模型
【发布时间】:2013-11-21 09:04:44
【问题描述】:

RAILS - 远程模型关联

基本上,我在使用has_many :through => 时遇到了一些困难

我有四个感兴趣的模型:

  1. 填字游戏
  2. 细胞
  3. 线索
  4. 单词

一个填字游戏有很多单元格,一个单元格有很多线索,一个线索属于一个单词

或者,视觉上:

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


【解决方案1】:

这里的问题不是我的联想,而是我的输入。

我的联想如下:

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

结案!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-05
    • 2018-10-15
    • 2011-09-22
    • 2012-05-23
    相关资源
    最近更新 更多