使用单选按钮从序列化数组更新rails数据库

时间:2012-01-03 01:26:46

标签: ruby-on-rails radio-button

我有一群拥有大量用户的数据库;在他们的属性中是他们想要工作的星期几的偏好(星期日......星期六,偏好范围从从不/很少/好/首选)。它存储在序列化的hash user.day_pref。

它显示正常,但似乎在提交时不会从表单更新。鉴于序列化存储,我无法完全处理这个问题。

%h3 Day of week preferences
- weekdays = I18n.t 'date.abbr_day_names'
- if @user.day_pref.nil?
  / - @user.day_pref = Hash.new {|hash, key| hash[key] = "1"}
  - @user.day_pref = { "0" => "2", "1" => "2", "2" => "2", "3" => "2", "4" => "2", "5" => "2", "6" => "2" }
- pref_name = ["Almost never", "Avoid", "Okay", "Preferred"]
- pref_color = ["red", "yellow", "green", "violet" ]

= form_for @user, :url => user_path(@user), :method => :put do |f|
  %table.table
    %th
      - for day in (0..6)
        %th= weekdays[day]
    %tr
      %td
        - for row in (0..3)
      %br
        = pref_name[row] + " "
        %span{:style => "color:" + pref_color[row]} ♦
      - for day in (0..6)
        %td
          %div
            - for row in (0..3)
              %br= radio_button_tag "@user.day_pref[" + day.to_s + "]", row.to_s, @user.day_pref[day.to_s] == row.to_s
  %tr
    %input{:type => "submit", :name => "day-pref-button", :value => "Update day of week preferences"}

日志似乎显示成功提交的数据(并且attr_accessible设置为day_pref),但只有预先存在的值被写入数据库,而不是用户选择的新值:

Started PUT "/user/1" for 127.0.0.1 at 2012-01-02 17:04:35 -0800
Processing by UserController#update as HTML
Parameters: {"utf8"=>"✓",    "authenticity_token"=>"/auMOXMVOcO4Yrys2FymMPMxi/g/AI3G67vZPcXCb8M=", "@user.day_pref"=>{"0"=>"1", "1"=>"1", "2"=>"1", "3"=>"1", "4"=>"1", "5"=>"2", "6"=>"2"}, "day-pref-button"=>"Update day of week preferences", "id"=>"1"}
User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", "1"]]
(0.4ms)  UPDATE "users" SET "updated_at" = '2012-01-03 01:04:35.213534', "day_pref" = '-   --
''0'': ''1''
''1'': ''2''
''2'': ''1''
''3'': ''3''
''4'': ''1''
''5'': ''2''
''6'': ''2''
' WHERE "users"."id" = 1
Redirected to http://0.0.0.0:3000/user/1
Completed 302 Found in 61ms

我知道我在这里犯了一些愚蠢的语法错误,可能在视图代码中的“radio_button_tag”中,但是在过去的一个月里,我一直无法弄清楚我的生活。任何指针都赞赏。

  
    

我正在回答我自己的问题,至少部分是这样。我向控制器添加了几行,以为它可能没有以可存储的方式从单选按钮数组中重新打包我的数据。

  
  # PUT /user/1
  # PUT /user/1.json
  def update

    @user = User.find(params[:id])

    # The following, when added, stores the radio button data properly
    if params["@user.day_pref"]
      @user.day_pref = params["@user.day_pref"]
    end

    respond_to do |format|
      if @user.update_attributes(params[:user])
        format.html { redirect_to @user, notice: 'User was successfully updated' }
        format.json { head :ok }
      else
        format.html { render action: "edit" }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

所以这个现在正在运行,但我不完全确定为什么我需要额外的代码行。

0 个答案:

没有答案