10

Imagine I have the following models:

class Translation < ActiveRecord::Base
  has_many :localizations
end

class Localization < ActiveRecord::Base
  belongs_to :translation
end

If I do this in ActiveAdmin:

ActiveAdmin.register Localization do
  form do |f|
    f.input :word
    f.input :content
  end 
end

The association for word will only allow me to choose from existing words. However, I'd like to have the option of creating a new word on the fly. I thought it may be useful to accept nested attributes in the localization model ( but then, I will only have the option of creating a Word, not selecting from existing ones ). How can I solve this problem?

2
  • In your ActiveAdmin how would you like to determine which is the current Translation - choosing it from a menu or stored in params (passed by url) ?
    – R Milushev
    Dec 14, 2012 at 10:11
  • I should be able to either select it from a menu, or create a new translation and a new localization ( all at once )
    – Geo
    Dec 14, 2012 at 13:23

1 Answer 1

10
+500

I think you can try using virtual attribute for this

Example(not tested)

class Localization < ActiveRecord::Base
  attr_accessor :new_word #virtual attribute 
  attr_accessible :word_id, :content, :new_word
  belongs_to :translation
  before_save do
     unless @new_word.blank?
       self.word = Word.create({:name =>  @new_word})
     end
  end
end

The main idea is to create and store new Word instance before saving localization and use it instead of word_id from drop-down.

ActiveAdmin.register Localization do
  form do |f|
    f.input :word
    f.input :content
    f.input :new_word,  :as => :string

  end 
end

There is great rails-cast about virtual attributes http://railscasts.com/episodes/167-more-on-virtual-attributes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.