我在玩我的第一个有很多通过关系我有三个模型。给你。

class User < ActiveRecord::Base
   # Include default devise modules. Others available are:
   # :confirmable, :lockable, :timeoutable and :omniauthable
   devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

   has_many :pools
   has_many :games,
            through: :pools
   end

~
class Pool < ActiveRecord::Base
     has_many :users
     has_many :games,
            through: :users
     end

~
class Game < ActiveRecord::Base
     belongs_to :user
     belongs_to :pool
 end

这个设置是否允许我在IRB中执行以下操作?
u=User.first
u.games

当我这样做时,我得到以下错误。
SystemStackError: stack level too deep
from /Users/ShiftedRec/.rvm/rubies/ruby-2.0.0-p353/lib/ruby/2.0.0/irb/workspace.rb:86
Maybe IRB bug!

我应该可以做你的游戏,和你的游泳池?
做一个pool.users和pool.games也不错。
我该如何更改我的模型设置,以便我可以访问这些方法…?
我一直在读,但读了很多遍有点困惑。
这也是我的计划
ActiveRecord::Schema.define(version: 20140408165647) do

create_table "games", force: true do |t|
t.integer  "pool_id"
t.integer  "user_id"
t.datetime "created_at"
t.datetime "updated_at"
end

add_index "games", ["pool_id", "user_id"], name: "index_games_on_pool_id_and_user_id", unique: true

create_table "pools", force: true do |t|
t.string   "name"
t.datetime "created_at"
t.datetime "updated_at"
t.integer  "user_id" #vestige of old approach
end

create_table "users", force: true do |t|
t.string   "email",                  default: "", null: false
t.string   "encrypted_password",     default: "", null: false
t.string   "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer  "sign_in_count",          default: 0,  null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string   "current_sign_in_ip"
t.string   "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
end

add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token",           unique: true

end

我很感激你的帮助!

最佳答案

由于关联的定义不正确,因此出现错误rails出错并进入递归。
更新您的模型PoolUser,如下所示:

class Pool < ActiveRecord::Base
  has_many :games
  has_many :users,
    through: :games
end

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
    :recoverable, :rememberable, :trackable, :validatable

  has_many :games
  has_many :pools,
    through: :games
end

您试图通过UserPoolGame之间创建m-m关系。
另外,从user_id表中删除pools,因为您已经通过join tablegames建立了关联。
另外,由于您在进行上述更改后处于rails console(而不是IRB)状态,因此使用console命令在reload!中重新加载rails环境。
阅读Rails指南中有关has-many-through-associations的更多信息。

10-01 07:01
查看更多