Is there an easier way of creating/choosing related data with ActiveAdmin?

后端 未结 1 1552
庸人自扰
庸人自扰 2021-02-14 09:45

Imagine I have the following models:

class Translation < ActiveRecord::Base
  has_many :localizations
end

class Localization < ActiveRecord::Base
  belong         


        
1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-14 10:24

    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

    0 讨论(0)
提交回复
热议问题