如何在Rails中为多个集合设置关系

时间:2016-03-01 01:08:41

标签: ruby-on-rails ruby ruby-on-rails-4

用户有很多游戏。一场比赛有很多方块。现在每个方块都有一个user_id,但我不会检查该用户是否有任何方块,而是该用户可以更改该方块的详细信息(它是否属于用户有权访问的游戏)。现在我想做这样的事情来检查权限。

Select * from squares 
left join games on squares.game_id = games.id
left join users on games.user_id = users.id
where squares.id =

@user.games.squares.find(1)

class User < ActiveRecord::Base
  has_many :games  

class Game < ActiveRecord::Base
  has_many :squares  

class Square < ActiveRecord::Base
  belongs_to :game

1 个答案:

答案 0 :(得分:1)

您可以通过更改

来执行此操作@user.squares.find(1)
class User < ActiveRecord::Base
  has_many :games 
end

class Game < ActiveRecord::Base
  has_many :squares
end

到这个

class User < ActiveRecord::Base
  has_many :games 
  has_many :squares through: :games
end

class Game < ActiveRecord::Base      
  has_many :squares
  belongs_to :user
end