我在通過訪問has_many上的一個額外參數的權限時遇到了麻煩。這可能很簡單。 我的3款機型均通過Rails在has_many上訪問其他值
class User < ActiveRecord::Base
has_many :players_users
has_many :players, through: :players_users
end
class Player < ActiveRecord::Base
has_many :players_users
has_many :users, through: :players_users
end
class PlayersUser < ActiveRecord::Base
belongs_to :user
belongs_to :player
validates :player_id, uniqueness: { scope: :user_id }
end
我控制器保存記錄沒有問題。將權限值添加到正確的連接表。
def create
@players = Player.new(players_params)
@user= current_user
if @players.save
@player = Player.last
@user.save && @user.players_users.create(:player_id =>@player.id, :permission =>"owner")
redirect_to '/players'
else
render 'new'
end
end
但是我似乎無法正常訪問 我試圖
perm = User.find(current_user).players_users.includes(:Permission)
if perm == "owner"
其中給出一個ActiveRecord :: AssociationNotFoundError,在PlayersUser沒有被發現命名爲「許可」關聯;也許你拼錯了嗎?
我也曾嘗試
perm = User.players_users.where(player_id = @player.id && user_id = current_user)
perm.permission
或
perm = User.Player.where(player_id = @player.id && user_id = current_user)
或
perm = User.players.where(player_id = @player.id && user_id = current_user)
其中給出一個未定義的方法錯誤。 undefined方法`玩家'
我知道這是在我的設置很小,但無法弄清楚它是什麼。任何幫助讚賞。
'User.find(current_user).players_users.first.permission'會給你第一個player_user的權限值。如果你想全部使用'User.find(current_user).players_users.first.pluck(:permission)' –