2012-07-22 106 views
1

我正在通过rails第4版(rails 3.2+)进行敏捷web开发。长话短说,我最终搞砸了一些东西,所以我从书本网站上将正确的代码复制到适当的文件中。具体来说,我正在进行一些功能测试,这是我替换的代码。当我跑:属性导致错误的方法

rake test:functionals 

我:

0 failures, 6 errors 

每个错误是这样的:

ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: 

面前处理了这个错误,我能推断出6个误差修改是来自我复制和粘贴的代码中的6个属性方法。下面是各种功能测试的一些例子:

test "should update cart" do 
    put :update, id: @cart, cart: **@cart.attributes** 
    assert_redirected_to cart_path(assigns(:cart)) 
    end 

test "should update order" do 
    put :update, id: @order, order: **@order.attributes** 
    assert_redirected_to order_path(assigns(:order)) 
    end 

test "should update line_item" do 
    put :update, id: @line_item, line_item: **@line_item.attributes** 
    assert_redirected_to line_item_path(assigns(:line_item)) 
    end 

现在,我也知道,错误的属性是由于B/C,他们消失了,如果我有一个哈希替换它们:

model: {attribute: value, attribute: value, attribute: value, etc. } 

代替:

model: @model.attributes 

所有被分配的属性都在我的模型的attr_accessible方法中。因此,我真的不知道为什么属性方法不起作用。任何和所有的帮助,将不胜感激。

回答

1

你确定当你用散列代替@model.attributes时,你放入了相同的属性吗?看起来像attributes方法返回的一些模型属性没有被attr_accessible列入白名单,但是当您将其替换为散列时,您只能使用列入白名单的方法。

+0

是的,你是完全正确的。错误的详细信息反映了这一点,因为当出现质量分配错误时,它会引用'updated_at','created_at'和'id'属性。好决定。 – flyingarmadillo 2012-07-22 10:29:51

+0

出于好奇,你知道任何只会输出白名单属性的方法或助手吗? – flyingarmadillo 2012-07-22 10:41:54

+1

嗯,快速猜测会使用像'@ model.attributes.slice(* Model.accessible_attributes)' – binarycode 2012-07-22 17:27:06

相关问题