4

我用Rails 3.2.8併爲每個級別一組名稱/答案對,其中一個用戶可以更新:視圖和用戶更新鍵/值的集合形式的Rails

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實例。

回答

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 

然後在適當的config/locales項添加到您的en.yml。你唯一需要寫的是:

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

我可能希望標籤和字段在助手中,但這看起來像正確的方法 –

+0

然後只需將標籤添加到助手。我沒有這樣做,因爲它可能會造成一些問題。 – Hauleth

+0

它可以造成什麼問題? –

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

我不知道ActiveRecord商店,看起來很有趣。基本上是一個文本字段。雖然我無法在數據庫的序列化字段中找到答案。 –