0

在一个模型中,我有这个:

class Game < ActiveRecord::Base
  has_one :turn

  attr_accessor :turn
  attr_accessible :turn

  default_scope :include => :turn

  def Game.new_game
    turn = Turn.create count: 1, phase: 'upkeep', player: 1
    game = Game.create turn: turn
    game
  end
end

class Turn < ActiveRecord::Base
  belongs_to :game
end

后来,在控制器中,我有这个:

respond_with Game.find(params[:id])

但是由于某种原因,返回的游戏有一个turn_idthat isnil并且没有关联的turn对象。

为什么关联没有正确保存,或者没有正确返回find()

在我的迁移中,我认为我已经正确设置了关联:

create_table :games do |t|
   t.timestamps
end

def change
 create_table :turns do |t|
   t.string :phase
   t.integer :count

   t.references :game
   t.timestamps
 end

结尾

4

2 回答 2

0

你似乎搞砸了联想

根据对场景的理解,这就是我的想法。

关联应该像

class Game < ActiveRecord::Base
  has_one :turn

  #.....
end

class Turn < ActiveRecord::Base
  belongs_to :game
  #.....
end

和像这样的迁移

create_table :games do |t|
  #add some columns
  t.timestamps
end


create_table :turns do |t|
  t.references :game
  #add some columns
  t.timestamps
end

现在添加新游戏并转

    game = Game.create 
    turn = game.turn.create  count: 1, phase: 'upkeep', player: 1

game.tun.creategame_id = game.id将使用和其他提供的 args自动创建转弯记录。

您的迁移问题是游戏指的是转,而不是应该相反。

在此处查找有关关联的更多信息 http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html http://guides.rubyonrails.org/association_basics.html

于 2012-08-14T18:17:00.477 回答
0

有些东西是颠倒的。

由于Turn 有belongs_to 语句,Turn 应该包含game_id,而不是相反。

因此,您无法访问 Game turn_id,因为该字段不存在。它将始终为零,如果您删除 has_one 语句,它将引发异常。

于 2012-08-22T16:04:26.507 回答