【问题标题】:Rails 4 Dynamic generate Hstore keys and automatically add it into whitelistRails 4 动态生成 Hstore 密钥并自动将其添加到白名单中
【发布时间】:2014-06-07 04:18:55
【问题描述】:

我在 UrlCommand 模型中有一个cgi_attributes hstore 类型列。

class UrlCommand < ActiveRecord::Base
    store_accessor :cgi_attributes, :name, :range, :security, :default_value
end

但是,cgi_attributes 中的键应该由用户动态添加。

而且我还想在我的表单中将每个键呈现为输入字段

而不是对列进行硬编码

  - [:name, :range, :security].each do | column |
    = render :partial => 'attributes' , :locals => { f: f, column: column }

并且还需要添加那些动态生成的密钥才能更新到我的模型中。

def url_command_params
  params.require(:url_command).permit(:model_name, :firmware_version, :cgi_attributes,
                                       :cgi_name,:name, :range, :security)

end

现在,我所有的代码都是基于硬编码的,如何让用户动态添加键和值并存储到 UrlCommand 模型中?

【问题讨论】:

  • @deep 它没有提到如何通过 ActiveRecord 访问这些密钥。
  • 我也有同样的问题。 store_accessor 需要动态更改以及如何显示/保存此类 hstore 数据

标签: ruby-on-rails ruby-on-rails-4 strong-parameters hstore


【解决方案1】:

也许您可以为属性名称 (CustomAttributes) 创建一个单独的表,然后创建一个循环,使用 store_accessor 添加它们,如下所示:

CustomAttributes.all.each do |attribute|
     store_accessor :cgi_attributes attribute.name
end

我猜你可以做一些类似于强参数的事情。我自己没有尝试过,因为我正在努力让 hstore 在我的应用程序中工作。但我将有相同的用户情况/问题要解决。因此,一旦我得到它的工作并得到确认,我将对其进行测试并更改我的答案。

有点像这个 railscast 中的解释: http://railscasts.com/episodes/403-dynamic-forms

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-14
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 2013-06-11
    相关资源
    最近更新 更多