2014-03-25 69 views
1

我有一個接受嵌套屬性的另一種模式,像這樣一個模型:Rails的接受嵌套屬性ATTR訪問命名

class House < ActiveRecord::Base 
    has_one :owner 

    attr_accessible :owner_attributes 

    accepts_nested_attributes_for :owner 
end 

我希望能夠調用:owner_attributes只是:owner,並能夠發佈的JSON看起來像這樣:

{ 
    "house": { 
    "address": "123 Main St", 
    "owner": { 
     "name": "Jim", 
     "age": 9000 
    } 
} 

這看起來像違背了軌道約定,但我只是想弄清楚它是否可能。

+0

我相信如果你使用的是軌道4,並張貼這一點,它會工作。如果你使用強參數,你只需要將'owner_attributes:[:name,:etc]'添加到params方法的'permit'方法中。當它到達控制器時,它將從'owner'轉換爲'owner_attributes'。所以'params.require(:house).permit(:house_field_a,:house_field_b,owner_attributes:[])' – CWitty

+0

我還沒有使用強大的參數(即將推出:D),但無論如何, 'owner'而不是'owner_attributes',這是行不通的。 – Cristiano

+0

您使用的是什麼版本的導軌? – CWitty

回答

0

添加到您的控制器

private 
def house_params 
    params.require(:house).permit(:house_field_a, :house_field_b, owner_attributes: [:name, :etc]) 
end 

這將owner參數轉換成owner_attributes讓您POST嵌套owner對象。

然後在控制器動作,您可以只使用house_params代替params[:house]