【问题标题】:cant use Activerecord find method with associations不能将 Activerecord 查找方法与关联一起使用
【发布时间】:2010-05-04 20:59:50
【问题描述】:

这是我的模型:

#game 
class Game < ActiveRecord::Base
  #relationships with the teams for a given game
  belongs_to :team_1,:class_name=>"Team",:foreign_key=>"team_1_id"
  belongs_to :team_2,:class_name=>"Team",:foreign_key=>"team_2_id"

  def self.find_games(name)
  items = Game.find(:all,:include=>[:team_1,:team_2] , :conditions => ["team_1.name = ?", name] )     
  end
end

#teams
class Team < ActiveRecord::Base
  #relationships with games
  has_many :games, :foreign_key  =>'team_1'
  has_many :games, :foreign_key  =>'team_2'
end

当我执行 Game.find_games("real") 我得到: ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: team_1.name

如何解决我认为使用 :include 可以解决问题的问题。

【问题讨论】:

    标签: ruby-on-rails ruby activerecord


    【解决方案1】:

    Team_1 不是表的名称。这些条件不适用于 ruby​​ 中定义的关联,但适用于表本身。条件应为::conditions =&gt; ["teams.name = ?", name]

    另外,我认为teams类是不正确的,你当然不能定义游戏两次,外键应该和belongs的一样:

    #teams
    class Team < ActiveRecord::Base
      #relationships with games
      has_many :team_1_games, :class_name => "Game", :foreign_key  =>'team_1_id'
      has_many :team_2_games, :class_name => "Game", :foreign_key  =>'team_2_id'
    end
    

    有一个更好的方法可以做到这一点,但我想不起来了。

    【讨论】:

    • 我尝试过它的工作,但它只在 team_1 中查找名称。我希望它同时查找属性 team_1 和 team_2。
    猜你喜欢
    • 1970-01-01
    • 2019-08-07
    • 2011-07-28
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多