Sunday, March 16, 2014

Nested forms for belongs_to relationship - ActiveAdmin

For my current project I had to add nested form for belongs_to relationship. After lots of searching i found a solution.

class Product < ActiveRecord::Base
 belongs_to :cost, :class_name => 'Currency', foreign_key: 'cost_id'
 accepts_nested_attributes_for :cost
 attr_accessor :cost_id
end
class Currency < ActiveRecord::Base
 def self.currency_types
   ['SAR','AED','USD','EUR','INR']
 end
end

ActiveAdmin.register Product do
 form do |f|
    f.semantic_errors *f.object.errors.keys
    f.inputs "Details" do
      f.input :name
      f.inputs "cost" do
         f.semantic_fields_for :cost_attributes  do |j|
            j.inputs do
              j.input :currency_type, :as => :select, :collection => Currency.currency_types,:label =>'Cost'
              j.input :value
            end
          end
        end
      end
    end
    f.actions
 end

 controller do
   def permitted_params
    params.permit product: [:name,cost_attributes:[:id,:currency_type,:value]]
   end
 end
end

1 comment:

  1. Your blog provided us with valuable information to work with. Thanks a lot for sharing. Keep blogging.

    Shop Online Equinox Nebulizer

    ReplyDelete