用户在Rails中更新键/值集合的视图和表单

时间:2012-09-21 08:30:04

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

我正在使用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实例的集合。

2 个答案:

答案 0 :(得分:3)

在助手中添加:

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

然后在en.yml的{​​{1}}中添加正确的密钥。你唯一需要写的是:

config/locales

答案 1 :(得分:0)

您熟悉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"