【问题标题】:Fields of hstore emptying if validation fail验证失败时 hstore 清空的字段
【发布时间】:2015-06-02 05:47:46
【问题描述】:

导轨 4.2 PostgreSQL 9.3.7

我正在使用hstore 以键值格式存储一些数据。

create_table "lang", force: :cascade do |t|
  t.string   "name"
  t.hstore   "dictionary"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

在模型中,我通过 store_accessor 使用了一些验证

store_accessor :dictionary, :foo, :bar
validates_presence_of :foo, :bar

new 部分slim 格式的操作视图:

= form_for(@lang) do |f|
  .field
    = f.label :name
    = f.text_field :name
  .field
    = f.fields_for :dictionary do |dic_form|
      fieldset
        = dic_form.label :foo
        = dic_form.text_field :foo
        br
        = dic_form.label :bar
        = dic_form.text_field :bar
  .actions = f.submit

为什么当验证检查失败时,我输入的所有数据都被清空了? 例如:我在foo 字段中只输入了test 文本,提交表单。查看错误说明,但 test 文本从 foo 字段中消失。

有什么方法可以像普通的 rails 表单一样让数据在请求之间保持不变?

【问题讨论】:

  • 能否请您展示您的控制器,并强调strong_params

标签: ruby-on-rails postgresql hstore


【解决方案1】:

问题在于rails 如何形成提取属性。 当我输入时

= form_for(@lang) do |f|
  .field
    = f.label :name
    = f.text_field :name

Rails 评估 @lang.name

所以当表单看起来像这样时

= f.fields_for :dictionary do |dic_form|
  .fieldset
    = dic_form.label :foo
    = dic_form.text_field :foo

@lang.dictionary.foo 代码没有结果。

这里的解决方案是像这样使用 OpenStruct:

= form_for(@lang) do |f|
  .field
    = f.label :name
    = f.text_field :name
  .field
    = f.fields_for :dictionary, OpenStruct.new(@translation.dictionary) do |dic_form|
      fieldset
        = dic_form.label :foo
        = dic_form.text_field :foo
        br
        = dic_form.label :bar
        = dic_form.text_field :bar
  .actions = f.submit

【讨论】:

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