【问题标题】:ActiveAdmin get value from form text fieldActiveAdmin 从表单文本字段中获取值
【发布时间】:2015-12-01 17:43:13
【问题描述】:

我是Ruby 的新手,使用ActiveAdmin 做了一些简单的管理员。 我有一个模型Question,我想创建、填充并存储到数据库中,它有一个属性themesTheme 模型数组)。当用户创建新记录时,他不会手动输入主题,而是提供一些字符串,系统会自动解析并查找或创建主题。所以我有这样的代码:

form do |f|
    f.inputs "Questions Details" do
      f.input :question, as: :string
      f.input :autocomplete_themes, hint: "You should enter here multiple themes,
      divide them with `,` or `;`"
    end
    f.actions
end

它创建了一个新字段autocomplete_themes 用于输入字符串,并且它不存在于模型Question 中。所以我想要的 - 是获取 autocomplete_themes 类似字符串的值,然后使用 split() 和我的自定义逻辑 - 但它给出了一个错误。

before_create do |question|
    array = []
    puts "******"
    puts :autocomplete_themes.text
    themeTitles = :autocomplete_themes.split(",") #split(/,|;/)
    for title in themeTitles do
      theme = Theme.find_by(title: title)
      theme = Theme.create(title: title) unless theme
      array << theme
    end
    question.themes = array
end

问题:我怎样才能得到autocomplete_themes 值作为字符串?谢谢!

更新: 据我了解here - 看起来类似,但将默认值设置为自定义字段时出现问题,但我需要从代码中获取其值。

【问题讨论】:

    标签: ruby-on-rails ruby forms activeadmin


    【解决方案1】:

    您没有指定遇到的错误,但根据您提供的信息,您不需要 autocomplete_themesQuestion 模型的真正数据库支持的属性,而是您只需要临时信息,以便您的 before_create 过滤器可以使用它来执行适当的逻辑。

    因此,您可以将autocomplete_themes 设为“虚拟属性”,类似于Question 实例的传统成员变量。

    class Question < ActiveRecord::Base
    attr_writter :autocomplete_themes
    attr_reader :autocomplete_themes
    
    ...other code
    end
    

    这将允许您执行以下操作:

    @question.autocomplete_themes = "1,2,3"
    themes_text = @question.auto_complete_themes
    

    最重要的是,ActiveAdmin 支持将表单输入分配给虚拟属性。所以你可以像这样保持你的表单:

    form do |f|
    f.inputs "Questions Details" do
      f.input :question, as: :string
      f.input :autocomplete_themes, hint: "You should enter here multiple themes,
      divide them with `,` or `;`"
    end
    f.actions
    end
    

    你的before_filter 看起来像这样:

    before_create do |question|
      array = []
      themeTitles = question.autocomplete_themes.split(",") #split(/,|;/)
      for title in themeTitles do
        theme = Theme.find_by(title: title)
        theme = Theme.create(title: title) unless theme
        array << theme
      end
      question.themes = array
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      相关资源
      最近更新 更多