对象不支持具有多对多关联的#inspect

时间:2013-06-27 06:55:32

标签: ruby-on-rails ruby activerecord many-to-many

我已经有一周这个问题,我不能再谷歌了。我被卡住了。 我有一个简单的模型游戏:

class Game < ActiveRecord::Base
  serialize :data, :history

  # attr_accessible :title, :body

  TIMES_PER_MOVE = [1,2,3,4,5]
  TIMES_PER_GAME = [5, 10, 15, 30]

  has_and_belongs_to_many :players, class_name: User

  def create_available(user)
    self.players << user
    self.save!
  end

end

模特用户:

class User < ActiveRecord::Base
  serialize :settings, Hash

  attr_accessible :first_name, :last_name, :phone, :email, :country, :birth_date, :password, :security_code, :invitation_token
  attr_writer :current_step


  has_and_belongs_to_many :games
  ...
end

我使用连接表创建它们之间的关联:

create_table :games_users, :id => false do |t|
      t.references :user
      t.references :game
end

一切看起来都不错? - 没办法!!!

当我创建游戏实例时:

def create
    @game = Game.new()

      respond_to do |format|
        if @game.create_available(current_user) # see this method in the model
          format.html { redirect_to @game, notice: 'Game was successfully created.' }
          format.json { render json: @game, status: :created, location: @game }
        else
          format.html { render action: "new" }
          format.json { render json: @game.errors, status: :unprocessable_entity }
        end
      end    
  end 

它说好的)那很好。我创造了一个游戏!但!!!控制台发生了什么:

>> Game.all
  Game Load (0.2ms)  SELECT `games`.* FROM `games` 
(Object doesn't support #inspect)

>> u  = User.find_by_id 1
u  = User.find_by_id 1
  User Load (0.2ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
#<User id: 1, last_name: "Ivanyshyn", first_name: "Ostap", password:...>

>> u.games
u.games
  Game Load (0.2ms)  SELECT `games`.* FROM `games` INNER JOIN `games_users` ON `games`.`id` = `games_users`.`game_id` WHERE `games_users`.`user_id` = 1
(Object doesn't support #inspect)

当我尝试在我看来这样的事情时:

= current_user.not_started_games.each do |game|
  = game.time_per_move

我的浏览器提供了一些我从未期望看到的东西(我甚至不使用任何地方:历史符号!!!!):

undefined method `new' for :history:Symbol

这个问题让我哭了。也许我正在创建错误的游戏实例?或者我的协会不好?

1 个答案:

答案 0 :(得分:3)

你的问题在这里:

class Game < ActiveRecord::Base
  serialize :data, :history
                   ^^^^^^^^

Serialize定义为:

serialize(attr_name, class_name = Object)

..它不需要多个可序列化的参数。 请参阅:
http://apidock.com/rails/ActiveRecord/AttributeMethods/Serialization/ClassMethods/serialize

你可能想要做的是:

class Game < ActiveRecord::Base
  serialize :data 
  serialize :history