2012-07-22 108 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