【发布时间】: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