Rails Kitchen

It's a place to write on stuff I learned recently.

Nested Forms for Belongs_to Relationship - ActiveAdmin

| Comments

For my current project I had to add nested form for belongs_to relationship. After lots of searching i found a solution.
1
2
3
4
5
class Product<ActiveRecord::Base
 belongs_to :cost, :class_name => 'Currency', foreign_key: 'cost_id'
 accepts_nested_attributes_for :cost
 attr_accessor :cost_id
end
1
2
3
4
5
class Currency < ActiveRecord::Base
 def self.currency_types
   ['SAR','AED','USD','EUR','INR']
 end
end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
ActiveAdmin.registerProductdo
 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

Comments