2017-07-09 95 views
1

我想通過序列化哈希來爲我的應用程序構建一個默認清單。我不知道如何將我的setup_checklist哈希中的信息提取到我的視圖中。任何幫助表示讚賞。查看序列化的哈希軌道

這裏是我的用戶模型

class User < ActiveRecord::Base 
    # Include default devise modules. Others available are: 
    # :confirmable, :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable, :confirmable 

    serialize :checklist, Hash 

    before_create :setup_checklist 

    private 

    def setup_checklist 
    self.checklist = { 
     "Organize Your Finances" => false, 
     "Approval Letter" => false, 
     "Get a Real Estate Agent and look for houses" => false, 
     "Find lawyer" => false, 
     "Get the mortgage" => false, 
     "Apprisal and inspection" => false, 
     "Close the deal" => false 
    } 
    end 
end 

我view.html.erb

<%= form_for :checklist do |f| %> 
    <%= f.check_box :checklist %> 
<% end %> 

我知道我還差得遠,但在正確的方向轉舵將是巨大的

回答

0

要顯示哈希中的複選框,您需要迭代哈希併爲每個元素創建一個複選框;例如:

<%= form_for @user do |f| %> 
    <% @user.checklist.each do |key, value| %> 
    <%= f.check_box key %> 
    <% end %> 
<% end %> 
0

可能不是最漂亮的,但是這似乎是爲我工作

view.html.erb

<%= form_for @user do |f| %> 
    <%= f.fields_for :checklist do |c| %> 
    <% @user.checklist.each do |todo, completed| %> 
     <%= c.check_box todo %>&nbsp;<%= c.label todo %><br /> 
    <% end %> 
    <% end %> 

    <%= f.submit %> 
<% end %> 

,然後在控制器

def update 
    @user = User.find(params[:id]) 
    @user.checklist.each do |todo, completed| 
    @user.checklist[todo] = params[:user][:checklist][todo] == "1" 
    end 
    @user.save 

    redirect_to action: :show, id: params[:id] 
end 

當然,您可以將該控制器代碼移動到您的模型或重構的update_checklist方法之類的東西上然而,爲你工作,但這應該讓你開始。

如果你用強的參數,可以你需要允許每個可能的清單值,它就會將它們設置爲「0」或「1」,而不是真或假,但控制器可

@user.update(params.required(:user).permit(checklist: ["Organize Your Finances", ...]))