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



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

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

一切看起来都很好?——没门!!!

当我创建Game:的实例时

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

这个问题让我哭了。也许我创建游戏实例不正确?或者我的关系不好?

您的问题在这里:

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

序列化定义为:

serialize(attr_name, class_name = Object)

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

你可能想做的是:

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

最新更新