NeverBe
NeverBe

Reputation: 5038

Filtered has_many relationship form

I have simple form to display a model with has_many relationship.

  form do |f|

    f.semantic_errors *f.object.errors.keys

    f.inputs do
      f.has_many :messages, allow_destroy: true, heading: 'Messages' do |f|
        f.input :title

      end
    end

    f.actions
  end

My question is: how to prefilter :messages before the from is shown? It depends on current_admin user.

Upvotes: 0

Views: 58

Answers (1)

Andrew Zelenets
Andrew Zelenets

Reputation: 113

NeverBe!

My solution is based on creating a custom has_many relation with condition for model. For example:

File /app/models/key.rb

class Key < ActiveRecord::Base

    attr_accessible :name,
                    :messages, :messages_attributes,
                    :messages_for_organization_attributes 

    has_many :messages, dependent: :destroy
    accepts_nested_attributes_for :messages, allow_destroy: true

    has_many :messages_for_organization, class_name: 'Message', conditions: proc {"organization_id" = #{$current_admin_user.organization_id}"}
    accepts_nested_attributes_for :messages_for_organization, allow_destroy: true

end

File /app/models/message.rb

class Message < ActiveRecord::Base

    attr_accessible :title,
                    :key, :key_id
                    :organization, :organization_id

    belongs_to :key
    belongs_to :organization

end

File app/admin/key.rb:

controller do

    def edit
      if current_admin_user.role?('super_admin')
        @key = Key.find_by_id(params[:id])
      else
        @key = Key.joins('LEFT JOIN messages ON messages.key_id = key.id').where(id: params[:id]).first
      end
      $current_admin_user = current_admin_user # Important assignment to get access current_admin_user in Key model class

      edit!
    end

end


form do |f|
    f.semantic_errors *f.object.errors.keys

    f.inputs do
        if current_admin_user.role?('super_admin')
            f.has_many :messages, allow_destroy: true, heading: 'Messages' do |f|
                f.input :title
            end
        else
            f.has_many :messages_for_organization, allow_destroy: true, heading: 'Messages' do |f|
                f.input :title
            end
        end
    end

    f.actions
end

Upvotes: 1

Related Questions