【问题标题】:Camping model ignores association露营模型忽略关联
【发布时间】:2011-09-27 19:37:29
【问题描述】:
module App::Models
  class Team < Base
    has_many :players
    [...]
  end

  class Player < Base
    belongs_to :team
  end

调用@team.players(或@player.team)时:

NoMethodError at /team/red
undefined method `players' for [#<App::Models::Team (...)>]:ActiveRecord::Relation

我是不是用错了?

【问题讨论】:

    标签: ruby activerecord camping


    【解决方案1】:

    请注意,您在 ActiveRecord::Relation 的实例上调用 players。您实际上没有一个团队,您有几个团队的查询。只需将.first 附加到您对@team 的定义中即可获得第一支队伍:

    class TeamX
      def get(name)
        @team = Team.where(:name => name).first
      end
    end
    

    【讨论】:

    • 哇,找到了!考虑到这根本不是问题,而是问题所在,干得好!另外,我有点尴尬,我犯了这么愚蠢的错误。好的,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多