Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/53.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails中有多少外键?_Ruby On Rails - Fatal编程技术网

Ruby on rails Rails中有多少外键?

Ruby on rails Rails中有多少外键?,ruby-on-rails,Ruby On Rails,我在一个AI竞赛的网站上工作,你可以上传一个pacman或Ghost控制器,对它们进行评估,结果显示在网站上 我有一张用于控制器的表,称为“代理”: class CreateAgents < ActiveRecord::Migration def change create_table :agents do |t| t.string :ctype # either 'pacman' or 'ghosts' t.references :user, :nul

我在一个AI竞赛的网站上工作,你可以上传一个pacman或Ghost控制器,对它们进行评估,结果显示在网站上

我有一张用于控制器的表,称为“代理”:

class CreateAgents < ActiveRecord::Migration
  def change
    create_table :agents do |t|
      t.string :ctype # either 'pacman' or 'ghosts'
      t.references :user, :null => false
      ...
      t.timestamps
    end
    ...
  end
end
通过使用带有相应外键的“所属对象”:

class Game < ActiveRecord::Base
  belongs_to :pacman, class_name: 'Agent', foreign_key: 'pacman_agent_id'
  belongs_to :ghosts, class_name: 'Agent', foreign_key: 'ghosts_agent_id'
end
这将返回特定控制器的游戏,如果是pacman或Ghost控制器,则独立返回

这是我尝试过的,但不起作用:

class Agent < ActiveRecord::Base
  belongs_to :user
  has_many :games, foreign_key: (:ctype == 'pacman' ? 'pacman_agent_id' : 'ghosts_agent_id')
end
类代理 有什么想法吗?也许我的数据库设计不正确

提前谢谢

有什么想法吗?也许我的数据库设计不正确

是的,这是绝对错误的!xD

与向一个模型添加两个id字段不同,您应该使用多态关联,该关联还需要两个字段,但一个包含类型(模型名称),另一个包含id。您可以在此处找到所需的所有内容:


刚开始有点复杂。还有一位railscast关于这个主题(#154)。

如果你不想使用多态关联,你可以使用这个:)

类游戏代理。按ctype(“吃豆人”)查找。吃豆人游戏
=>代理。按ctype(“鬼魂”)查找。鬼魂游戏
=>游戏。第一。吃豆人
=>游戏。第一。幽灵

S..t,我知道我的设计有问题。这是我学习Rails的第三周,我将阅读更多关于多态关联的内容。谢谢
class Game < ActiveRecord::Base
  belongs_to :pacman, class_name: 'Agent', foreign_key: 'pacman_agent_id'
  belongs_to :ghosts, class_name: 'Agent', foreign_key: 'ghosts_agent_id'
end
Agent.first.games
class Agent < ActiveRecord::Base
  belongs_to :user
  has_many :games, foreign_key: (:ctype == 'pacman' ? 'pacman_agent_id' : 'ghosts_agent_id')
end
class Game < ActiveRecord::Base
  belongs_to :pacman, class_name: 'Agent', foreign_key: :pacman_agent_id
  belongs_to :ghosts, class_name: 'Agent', foreign_key: :ghosts_agent_id
end


class Agent < ActiveRecord::Base
  belongs_to :user
  has_many :pacman_games, class_name: 'Game', foreign_key: :pacman_agent_id
  has_many :ghost_games, class_name: 'Game', foreign_key: :ghosts_agent_id
end

=> Agent.find_by_ctype('pacman').pacman_games
=> Agent.find_by_ctype('ghosts').ghost_games

=> Game.first.pacman
=> Game.first.ghosts