【问题标题】:Ruby on rails ActiveRecord Relation not working?Ruby on rails ActiveRecord 关系不起作用?
【发布时间】:2015-08-04 23:44:45
【问题描述】:

我的 ActiveRecord::Relation 不起作用我有 3 个 Db 的用户、游戏、成就他们之间定义的关系是这样的

用户

has_many :games

游戏

belongs_to :user
has_many :achievements

成就

belongs_to :game

问题是当我尝试打电话时

Game.where(:appid => game["appid"]).achievements.new

它给了我一个错误的说法

undefined method `achievements' for #<Game::ActiveRecord_Relation:0x730f9f8>

我在 Ruby on Rails 4.1.8 上运行,但我不知道为什么会发生这种情况(我的成就表中确实有 belongs_to :game,index: true 列,我想不出它为什么不起作用)

【问题讨论】:

    标签: ruby-on-rails ruby activerecord


    【解决方案1】:

    你在这里得到一个关联:

     Game.where(:appid => game["appid"])
    

    ...这实现为一个对象数组(即使sql没有返回记录,那么它仍然是一个数组,虽然它是空的)。

    你需要选择其中一个……可能是第一个,像这样:

     Game.where(:appid => game["appid"]).first.achievements.new
    

    或者你可以遍历这些值:

     Game.where(:appid => game["appid"]).each { |game| game.achievements.new }
    

    或类似的。

    【讨论】:

    • 谢谢我没有注意到所有查询总是以数组的形式返回,谢谢问题现在已经解决了!
    【解决方案2】:

    或许,你应该选择一个模型

    Game.where(:appid => game["appid"]).first
    

    然后得到关系模型

    .achievements.new
    

    【讨论】:

      【解决方案3】:

      答案在例外中。 #where 返回一个 ActiveRecord_Relation,而不是一个游戏,即使关系中只有一个游戏。所以你真的有一个可枚举的。即:

      puts Game.where(:appid => game["appid"]).first.achievements.new
      

      如果你只想要第一个符合条件的游戏,你可以使用 find_by

      Game.find_by(:appid => game["appid"])
      

      但我不确定这就是你要找的东西

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-02-23
        • 1970-01-01
        • 2021-05-25
        • 1970-01-01
        • 1970-01-01
        • 2018-12-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多