有没有使用ActiveAdmin创建/选择相关数据的简便方法? [英] Is there an easier way of creating/choosing related data with ActiveAdmin?

查看:34
本文介绍了有没有使用ActiveAdmin创建/选择相关数据的简便方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下我有以下模型:

Imagine I have the following models:

class Translation < ActiveRecord::Base
  has_many :localizations
end

class Localization < ActiveRecord::Base
  belongs_to :translation
end

如果我这样做ActiveAdmin:

If I do this in ActiveAdmin:

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

单词关联仅允许我从现有单词中进行选择。但是,我希望可以即时创建一个新单词。我认为在本地化模型中接受嵌套属性可能很有用(但是,我只能选择创建一个Word,而不从现有属性中进行选择)。我该如何解决这个问题?

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?

推荐答案

我认为您可以尝试为此使用虚拟属性

I think you can try using virtual attribute for this

示例(未经测试)

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

主要思想是在保存本地化之前创建并存储新的Word实例,并使用它代替下拉菜单中的word_id。

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

很棒的滑轨-投射虚拟属性 http://railscasts.com/episodes/167-more-on -虚拟属性

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

这篇关于有没有使用ActiveAdmin创建/选择相关数据的简便方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆