Rails如何从另一个模型的表单向另一个控制器发布数据

时间:2017-06-17 08:53:12

标签: ruby-on-rails forms controller routes

所以我有模特合同和员工。从员工的节目HTML我希望能够为该特定员工添加合同。

这是我的show html

中的一行
- hosts: localhost
  tasks:
  - set_fact:
          all_vars: "{{all_vars | default([]) |union([item.key + ':{{' + item.key + '|to_json}}'])}}"
    when: "{{not item.key.startswith('ansible_')}}"
    with_dict: "{{vars}}"
  - copy:
      content: "{{ all_vars | join('\n') }}"
      dest: "/tmp/tmp1.yml"
  - template:
      src: "/tmp/tmp1.yml"
      dest: "/tmp/tmp.yml"

和我在合同控制器中的创建功能

<%= link_to 'Add Contract', new_contract_path(@employee) %>

修改

在farhan的建议之后,这就是我的代码看起来像

def create
  puts "HERE IS"
  puts params[:id]
  puts "END"
  #create contract here for employee
end

我的new.html

def new
 @contract = Employee.find_by_id(params[:employee_id]).contracts.new
end
def create
 @employee = Employee.find_by_id(params[:employee_id])
 @contract = Employee.find_by_id(params[:employee_id]).contracts.build(contract_params)
 ...
end

和我的_form.html

<h1>New Contract</h1>
<%= render 'form', contract: @contract%>
<%= link_to 'Back', employee_contracts_path(employee_id: @employee) %>

但如果我到了网址<%= form_for(contract) do |f| %> ... <% end %> rails说 enter image description here

路线enter image description here

1 个答案:

答案 0 :(得分:0)

在您的终端中运行rake routes,在提交该表单后,您会看到new_contract_path(@employee)正在查找包含操作new的表单,它会转到create操作。此外,如果您想要嵌套路线,那么它应该是

resources :employees do
  resources :contracts
end

您需要创建名为new.html.erb的表单。

<强>更新

更新routes.rb后,您的路径助手也会改变,

在你看来,

<%= link_to 'Add Contract', new_employee_contract_path(employee_id: @employee) %>

在你的控制器中,

def create
  #assuming Employee has_many contracts
  contract = Employee.find_by_id(params[:employee_id]).contracts.build(contract_params)
  if contract.save
    #success case
  else
    #failure
  end
end

def new
  @contract = Employee.find_by_id(params[:employee_id]).contracts.new
end

private

def contract_params
  #permit required params
end
相关问题