【问题标题】:Views and forms for users updating key/value collections in Rails用户在 Rails 中更新键/值集合的视图和表单
【发布时间】:2012-09-21 08:30:03
【问题描述】:

我正在使用 Rails 3.2.8,并且对于用户可以更新的每个级别都有一组名称/答案对:

class UserAnswer < ActiveRecord::Base
  attr_accessible :name, :answer, :level_id, :user_id
end

创建这么多视图真是太痛苦了:

<li<%if @error_fields.include?('example_name') or @error_fields.include?('example_other_name')%> class="error_section"<%end%>>
  <%= label_tag 'answer[example_name]', 'Example question:' %> <%= text_field_tag 'answer[example_name]', @user_answers['example_name'], placeholder: 'Enter answer', class: @error_fields.include?('example_name') ? 'error_field' : '' %>
  <%= label_tag 'answer[example_other_name]', 'Other example question:' %> <%= text_field_tag 'answer[example_other_name]', @user_answers['example_other_name'], placeholder: 'Enter other answer', class: @error_fields.include?('example_other_name') ? 'error_field' : '' %>
</li>

@user_answers 显然是保存用户上次更新答案的哈希值。上面重复的太多了。在 Rails 中处理这个问题的最佳方法是什么?我很想使用form_for 之类的东西,但我认为我不能这样做,因为这不是单个模型对象,而是UserAnswer ActiveRecord 实例的集合。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord ruby-on-rails-3.2 erb


    【解决方案1】:

    在助手中添加:

    def field_for(what, errors = {})
      what = what.to_s
      text_field_tag("answer[#{what}]",
        @user_answers[what], placeholder: l(what),
        class: @error_fields.include?(what) ? 'error_field' : '')
    end
    

    然后在config/locales 中为您的en.yml 添加正确的密钥。你唯一需要写的是:

    <%= label_tag 'answer[example_name]', 'Example question:' %> <%= field_for :example_name, @error_fields %>
    

    【讨论】:

    • 我可能想要帮助器中的标签和字段,但这看起来是正确的方法
    • 然后只需将标签添加到助手。我没有这样做,因为它会产生一些问题。
    • 带有翻译/显示正确的信息,但如果你认为它会很简单:)
    【解决方案2】:

    你熟悉 Rails 3.2 ActiveRecord Store吗?

    这似乎是一种更简单的存储键/值的方法,您只需说@user_answer.example_name 而不是answer[example_name]。然后,您可以在表单中添加一个 example_name 字段。

    class UserAnswer < ActiveRecord::Base
      store :answers, accessors: [:example_name, :example_other_way]
    end
    
    answer = UserAnswer.new(example_name: "Example Name")
    answer.example_name returns "Example Name"
    

    【讨论】:

    • 我不知道 ActiveRecord Store,看起来很有趣。基本上是一个文本字段。虽然我无法在数据库的序列化字段中找到答案。
    猜你喜欢
    • 2016-09-24
    • 1970-01-01
    • 2021-04-12
    • 2018-11-16
    • 2019-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多