Rails与has_many的子集形成:通过复选框

时间:2014-05-13 09:40:20

标签: ruby-on-rails ruby forms ruby-on-rails-4 has-many-through

我有一个相当简单的应用程序,使用Abilities作为连接表,将Users分配给Permissions。我已经在下面列出了模型定义。

但是,Abilities也属于Client。向用户添加能力的表单仅包含特定客户的能力

由于表单只返回该客户端的已检查 ability_ids,如果我只是使用

@user.update(params[:user].permit({:ability_ids => []}))

表格

= simple_form_for(@user, url: user_permissions_path, method: :patch do |f|
  = f.hidden_field :client_id, value: @client.id, name: :client_id
  = f.association :abilities, as: :check_boxes, collection: @client.abilities

然后为该用户删除所有其他客户端应用程序的所有权限。这是我目前正在使用的控制器更新代码,但我非常有信心有更多'Rails方式'可以做到这一点。

# permissions_controller#update

# Filter empty elements
update_abilities  = params[:user][:ability_ids].reject { |c| c.empty? }

# Get list of current ability ids
current_abilities = @user.abilities.for_client(@client).pluck(:id).collect{ |i| i.to_s }

abilities_for_deletion = @user.permissions.where(ability_id: current_abilities - update_abilities)
abilities_for_deletion.delete_all unless abilities_for_deletion.empty?

abilities_for_addition = Ability.find(update_abilities - current_abilities)
@user.abilities.push(abilities_for_addition)

class User < ActiveRecord::Base
  has_many :permissions, dependent: :destroy
  has_many :abilities, through: :permissions do
    def for_client(client)
      where('abilities.client_id' => client.id)
    end
  end
end

class Permission < ActiveRecord::Base
  belongs_to :ability
  belongs_to :user
end


class Ability < ActiveRecord::Base
  has_many :permissions, dependent: :destroy
  belongs_to :client
end

我问,因为我现在需要通过相同的表单修改用户组,该表单也属于特定的客户端,并且需要大量复制此更新代码。

感谢。

0 个答案:

没有答案