gpt4 book ai didi

ruby-on-rails - simple_form 关联访问用户没有访问权限的记录

转载 作者:太空宇宙 更新时间:2023-11-03 17:51:01 25 4
gpt4 key购买 nike

我有一个具有简单关联模型的 Rails 4 应用程序。

用户.rb

has_many :opportunities
has_many :customers
has_many :accounts

机会.rb

belongs_to :user
belongs_to :account

客户.rb

belongs_to :user
belongs_to :account

account.rb

belongs_to :user
has_many :opportunities, dependent: :destroy
has_many :customers, dependent: :destroy

这是客户 Controller

def index
@customers = Customer.accessible_by(current_ability)
end

def show
@customers = Customer.find(params[:id])
@customer.user = current_user
authorize! :show, @customer
end

def new
@customer = Customer.new
@customer.user = current_user
authorize! :new, @customer
end

def edit
@customer = Customer.find(params[:id])
@customer.user = current_user
authorize! :edit, @customer
end

我有能力控制的CanCan;

class Ability
include CanCan::Ability

def initialize(user)
user ||= User.new # guest user (not logged in)
if user.has_role? :admin
can :manage, :all
end
can :manage, Account, user_id: user.id
can :manage, Opportunity, user_id: user.id
can :manage, Customer, user_id: user.id
end
end

我正在使用 simple_form 为客户添加帐户关联。

<%=f.association :account,:label => 'Customer Account Name', label_method: :account_name, value_method: :id, include_blank: '-- Select One --' %>

问题是关联标签似乎能够访问数据库中的所有帐户,而不仅仅是那些与用户关联的帐户。我无法理解关联标签似乎忽略了任何限制。

gem 版本 rails , 4.0.4simple_form, 3.0.2“康康”

最佳答案

默认情况下,简单表单将只包含关联的所有项目。为了限制下拉列表中的选项,您需要像这样设置 collection 属性并仅传入用户可以访问的记录,例如:

<%= f.association :account, :label => 'Customer Account Name', label_method: :account_name, value_method: :id, include_blank: '-- Select One --', collection: Account.accessible_by(current_ability) %>

关于ruby-on-rails - simple_form 关联访问用户没有访问权限的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24713040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com