2017-07-18 65 views
1

我有一个拥有许多“优先级”的父“帐户”。在Ruby on Rails中更新子协会表格

我可以很容易地为这些帐户创建新的优先级,但是一旦创建它们,我就无法编辑/更新它们。

Account模型(父):

class Account < ApplicationRecord 
    has_many :priorities 
    accepts_nested_attributes_for :priorities 
end 

优先模式(子):

class Priority < ApplicationRecord 
    belongs_to :account 
end 

路线:

resources :accounts do 
    resources :priorities 
    end 

priorities_controller.rb(只是编辑,更新和params)

class PrioritiesController < ApplicationController 

    def edit 
    @account = Account.find(params[:account_id]) 
    @priority = @account.priorities.find(params[:id]) 
    end 

    def update 
    @account = Account.find(params[:account_id]) 
    @priority = @account.priorities.update(priority_params) 

    end 

    private 
    def priority_params 
     params.require(:priority).permit(:name, :narrative, :kpis) 
    end 

end 

最后,我edit.html.erb(所以这最终被帐户/#/优先级/#/编辑)

<%= form_for(@account) do |a| %> 

<%= a.fields_for :priorities, @priority do |p| %> 
    <p> 
    <%= p.label :name %><br> 
    <%= p.text_field :name %> 
    </p> 

    <p> 
    <%= p.label :narrative %><br> 
    <%= p.text_area :narrative %> 
    </p> 

    <p> 
    <%= p.label :kpis, "KPIs" %><br> 
    <%= p.text_field :kpis %> 
    </p> 

    <p> 
    <%= p.submit %> 
    </p> 
<% end %> 
<% end %> 

一切进展得很好,直到这一点。表单完美地获取正确优先级的表单数据,如果您尝试输入与该帐户ID无关的优先级ID,它甚至会失败。然而,当我点击“更新优先级”,我得到:

“动作‘更新’无法找到AccountsController”

现在,我可以按照错误,并创建该控制器的更新,但我认为它甚至不应该试图触发AccountsController,它似乎应该试图使用优先级控制器。

事实上,如果我检查控制台,请求似乎是怎么回事: 请求URL:http://127.0.0.1:3000/accounts/2

对不起,我已经寻找至少10小时为回答这个问题,并能找不到它。谢谢你的帮助。

+0

可能重复[form \ _for with nested resources](https://stackoverflow.com/questions/2034700/form-for-with-nested-resources) – jvillian

回答

0

this答案,this答案的讨论,我认为你需要做的是这样的:

<%= form_for [@account, @priority] do |f| %> 
    blah blah 
<% end %> 

(公平归属:直接从第二联动答案解禁)

正如你所指出的,这样的:

<%= form_for(@account) do |a| %> 

将要产生的的update行动网址10。因为,这正是导轨的工作原理。如果您想要嵌套资源的URL,则需要在form_for声明中包含这两个实例变量。

+0

好吧,所以这似乎是正确的方向,但是当我测试更新时,它更改了该帐户中的所有优先级 - 所以我必须在控制器中出现问题。谢谢。 – Jake

+0

是的,我改变了优先级更新控制器,它工作。非常感谢! – Jake