问题描述
我真的很难通过has_many访问一个名为Permission的附加参数的值。这可能很简单。
我的3个模型是
I am having real trouble accessing the value of an additional parameter called permission on a has_many through. It is probably something simple.My 3 Models are
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
我的控制器保存记录而没有问题。将权限值添加到正确的联接表中。
My controller saves the record without issue. Adding the permission value to the correct joining table.
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
但是我似乎无法正确访问它
我尝试过
However I seem unable to access it properlyI have tried
perm = User.find(current_user).players_users.includes(:Permission)
if perm == "owner"
哪个给出了ActiveRecord :: AssociationNotFoundError,在PlayersUser上找不到名为 Permission的关联;也许您拼错了?
Which gives an ActiveRecord::AssociationNotFoundError, association named 'Permission' was not found on PlayersUser; perhaps you misspelled it?
我也尝试过
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)
哪个给出了未定义的方法错误。
未定义方法`Player'
Which gives an undefined method error.undefined method `Player'
我知道这在我的设置中很小,但无法弄清楚它是什么。
I know this is something small in my setup but cannot figure out what it is. Any help appreciated.
推荐答案
players_users
和玩家
与User对象相关联,因此您可以将结果提取为
players_users
and players
are associated with User object, so you can fetch the results as,
current_user.players_users.pluck(:permission)
这篇关于通过Rails在has_many上访问其他值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!