simple_form关联访问用户没有访问轨道的记录

时间:2014-07-12 12:43:56

标签: ruby-on-rails ruby ruby-on-rails-4 simple-form cancan

我有一个Rails 4 App,它有一个简单的关联模型。

user.rb

has_many :opportunities
has_many :customers
has_many :accounts

opportunity.rb

belongs_to :user
belongs_to :account

customer.rb

belongs_to :user
belongs_to :account

account.rb

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

这是客户控制器

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 --' %>

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

宝石版本 rails4.0.4 simple_form3.0.2 “康康舞”

1 个答案:

答案 0 :(得分:4)

默认情况下,简单表单只包含关联的所有项目。为了限制下拉列表中的选项,您需要像这样设置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) %>