簡體   English   中英

在route.rb中使用自定義to_param的嵌套資源時,如何允許強參數創建/更新以允許?

[英]With Nested Resources in routes.rb with custom to_param, how can Strong Parameters allow created/update to permit?

我找不到能指引正確方向的東西。 嵌套資源中的每個其他accepts_nested_attributes_for似的問題似乎都可以在accepts_nested_attributes_for …附近解決,而我並不想這樣做。 我不是要從父母那里拯救孩子,而是要直接從孩子那里拯救孩子。

在我的routes.rb中,我嵌套了資源

resources :parents, param: :parent do
  resources :children, param: :child
end

parent表和child表都有自己的id列,但分別在parentchild列上具有唯一索引,我將在URL中使用它而不是id

http://example.com/parents/parent/children/child

這樣可以很好地瀏覽每個控制器的showeditindex動作。

問題是存在保存數據的異常。

我希望問題的根本原因不會歸結為child表中的字段也稱為child因為這就是我在模型中重寫to_param所需要的,並且需要保持這種方式。

導航到編輯屏幕: http : //example.com/parents/harry/children/sally/edit並在表單上推送Submit ,返回此NoMethodError異常:

在/ parents / harry / children / sally處出現NoMethodError
未定義的方法“ permit”,用於“ sally”:字符串

我確定問題是與children_controller.rb強參數”行有關。 我可以添加require :parent:child的哈希嗎?

def children_params
  params.require(:child).permit(:child, :date_of_birth, :nickname)
end

更新1(添加的參數):這是請求參數:

{
  "utf8"=>"✓", 
  "_method"=>"patch", 
  "authenticity_token"=>"fAkBvy1pboi8TvwYh8sPDJ6n2wynbHexm/MidHruYos7AqwlKO/09kvBGyWAwbe+sy7+PFAIqKwPouIaE34usg==", 
  "child"=>"sally", 
  "commit"=>"Update Child", 
  "controller"=>"children", 
  "action"=>"update", 
  "parent_parent"=>"harry"
}

發生錯誤時其他實例變量作用域內:

@父母

<Parent id: 1, parent: "harry", description: "", user_id: 1, created_at: "2015-06-27 12:00:15", updated_at: "2015-06-27 12:00:15">

@兒童

<Child id: 1, child: "sally", date_of_birth: nil, parent_id: 1, nickname: nil, created_at: "2015-06-27 12:00:15", updated_at: "2015-06-27 12:00:15">

params中 ,您需要像下面這樣更改children_params

def children_params
  params.permit(:child, :date_of_birth, :nickname) 
end

事實證明,問題似乎確實是因為模型屬性在模型上被命名為相同的屬性,這也稱為params哈希(真正的問題似乎在這里)。

我要做的就是重命名params哈希。

children_controller.rb ,我必須更改:

def children_params
  params.require(:child).permit(:child, :date_of_birth, :nickname)
end

至…

def children_params
  params.require(:anything_else).permit(:child, :date_of_birth, :nickname)
end

然后從以下位置在new / edit視圖中更改form_for我的表單:

<%= simple_form_for([@parent, @child]) do |f| %>

至…

<%= simple_form_for([@parent, @child], as: :child_params) do |f| %>

現在,無論是在測試中還是在用戶正常通過UI使用網站時,所有工具都可以正常運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM