Views and forms for users updating key / value collections in Rails

I use Rails 3.2.8 and have a set of name / response pairs for each level at which the user can update:

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

It’s such a pain to create many views:

 <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 is obviously a hash containing user responses from the latest update. There are so many repetitions above. What is the best way to handle this in Rails? I would like to use something like form_for , but I do not think it is possible, because this is not one model object, this is a collection of UserAnswer ActiveRecord instances.

+4
source share
2 answers

In the helpers add:

 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 

Then add the correct keys to your en.yml in config/locales . The only thing you need to write:

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

Are you familiar with the Rails 3.2 ActiveRecord Store ?

It seems to be a lot easier to store the key / value and just lets say @user_answer.example_name instead of answer[example_name] . Then you can just have the example_name field in your form.

 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" 
0
source

Source: https://habr.com/ru/post/1435454/


All Articles