Rails:保存属性不起作用

时间:2012-07-06 02:11:14

标签: ruby-on-rails

我有一个库(mylib.rb),我在其中定义了一些类和方法。它可供控制器和视图使用(我已经验证过)。

在mylib.rb中,我有:

def admins_filled (params)
  if params[:admin_selections]
    return TRUE
  end
end

def return_admins_json (params)
  admins_list = Array.new
  params[:admin_selection].each do |admin_id|
    admins_list << admin_id
  end
  return JSON.generate (admins_list)
end

在我的categories_controller.rb中,我有以下内容:

line 63:  def update
line 64:     @category = Category.find(params[:id])
line 65:    if admins_filled(params)
line 66:      params[:admins] = return_admins_json (params)
line 67:      respond_to do |format|
line 68:        if @category.update_attribute(:admins,params[:admins])
line 69:          format.html { redirect_to @category, notice: 'Category was successfully updated.' }
line 70:          format.json { head :no_content }
line 71:        end
line 72:      end
line 73:    end
line 74:
line 75:    respond_to do |format|
line 76:      if @category.update_attributes(params)
line 77:        format.html { redirect_to @category, notice: 'Category was successfully updated.' }
line 78:        format.json { head :no_content }
line 79:      else
line 80:        format.html { render action: "edit" }
line 81:        format.json { render json: @category.errors, status: :unprocessable_entity }
line 82:      end
line 83:    end
line 84: end

我收到以下错误:

Can't mass-assign protected attributes: utf8, _method, authenticity_token, commit, action, controller, id

应用程序跟踪:

app/controllers/categories_controller.rb:75:in `block in update'
app/controllers/categories_controller.rb:63:in `update'

以下是请求参数:

参数:

{"utf8"=>"✓",
 "_method"=>"put",
 "authenticity_token"=>"2xffx/uGVqo8/4aH7xEes0QL1Exjwa12p9g7HbEmBe0=",
 "admin_selections"=>{"admin1"=>"55",
 "admin2"=>"56",
 "admin3"=>"",
 "admin4"=>"",
 "admin5"=>"",
 "admin6"=>"",
 "admin7"=>"",
 "admin8"=>""},
 "commit"=>"Update Category",
 "id"=>"3",
 "admins"=>"[\"55\",
\"56\",
\"\",
\"\",
\"\",
\"\",
\"\",
\"\"]"}

我原本希望更新admins列,但看起来所有的params都会被传递。我不明白发生了什么。

添加categories.rb(模型):

class Category < ActiveRecord::Base
  attr_accessible :admin1, :admin2, :admin3, :admin4, :admin5, :admins, :board1, :board10, :board2, :board3, :board4, :board5, :board6, :board7, :board8, :board9, :board_members, :curator1, :curator10, :curator2, :curator3, :curator4, :curator5, :curator6, :curator7, :curator8, :curator9, :curators, :description, :mission_statement, :name
  attr_accessible :admins, :curators, :board_members, :admin_selections
  has_many :events
end

1 个答案:

答案 0 :(得分:2)

您的错误消息告诉您确切的错误,它不会让您批量转让。

rails 3.2.3发生了变化,要求您明确允许批量分配

config.active_record.whitelist_attributes = false 
关于变更的

See here

或者,您可以为您希望能够更改的模型中的属性设置attr_accessible,而不是允许批量分配,例如。

attr_accessible :admin_selection, :commit # etc