如何从另一个模型预填充ActiveAdmin表单值?

时间:2014-08-18 17:24:34

标签: ruby-on-rails ruby activeadmin rails-activerecord

在下面的代码中,如何使用另一个模型的值将预填充的表单字段填充到ActiveAdmin表单中:

ActiveAdmin.register Person do

  index do
    column :forename
    column :surname
    column :code do |p|
      MyCode.find_by_person_id(p.id).code
    end
    column :updated_at
    default_actions
  end

  filter :forename
  filter :surname

  form do |f|
    f.inputs "Person" do
      f.input :forename
      f.input :surname
      # How to get a value here, e.g. MyCode.find_by_person_id(p.id).code as above
      #f.input :code, :input_html => { :value => value??? }, as: :hidden
    end
    f.actions
  end
end

2 个答案:

答案 0 :(得分:11)

作为nistvan commented abovehas_one关系将相关对象提取到表单对象中,因此我的问题可以通过以下方式解决:

ActiveAdmin.register Person do

  index do
    column :forename
    column :surname
    column :code do |p|
      MyCode.find_by_person_id(p.id).code
    end
    column :updated_at
    default_actions
  end

  filter :forename
  filter :surname

  form do |f|
    f.inputs "Person" do
      f.input :forename
      f.input :surname
      f.input :code, :input_html => { :value => f.object.my_code.code }, as: :hidden
    end
    f.actions
  end
end

答案 1 :(得分:1)

如果在你的模型中有一个Person has_one Code,那么f.input :code将正常工作。您也不必在索引块中明确确定代码,只需:column :code

http://guides.rubyonrails.org/association_basics.html#the-has-one-association