加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 用户在Rails中更新键/值集合的视图和表单

发布时间:2020-12-17 02:18:54 所属栏目:百科 来源:网络整理
导读:我正在使用Rails 3.2.8,并且每个级别都有一组名称/答案对,用户可以在其中更新: class UserAnswer ActiveRecord::Base attr_accessible :name,:answer,:level_id,:user_idend 创建许多视图真是太痛苦了: li%if @error_fields.include?('example_name') or @
我正在使用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实例的集合.

解决方法

在助手中添加:

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 %>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读