在RoR中编写嵌套表单 [英] Writing Nested Form in RoR

查看:100
本文介绍了在RoR中编写嵌套表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在ROR中编写嵌套表单。
我有两个表 Employee EmployeeInfo ,并且这两个表都有一个名为 employeeID
这些表与这个键连接。
我想要做的是创建一个带有一些输入字段的表单,这些字段应该将值更新到两个表中。例如,我希望一个表单可以创建或更新名为 employee_name age 地址的字段以及 city 但是 employee_name age 出现在表员工城市地址出现在表格 EmployeeInfo
所以我应该怎么写表单标签来做到这一点。
如果问题是一个错误,请对不起。我真的很新鲜。请帮助

解决方案

扩展 @ emu's 答案



 #employee.rb 
班员工< / p> ActiveRecord :: Base
has_one:employe_info
accep_nested_attributes_for:employee_info
end
$ b#employee_info.rb
EmployeeInfo类< ActiveRecord :: Base
belongs_to:employee
end

控制器

 类EmployeesController< ApplicationController 

def new
@employee = Employee.new
@ employee.build_employee_info
end

def create
@employee = Employee.new(employee_params)

if @ employee.save
redirect_to @employee
else
render'new'
end
end

私人

def employee_params
params.require(:employee).permit(:employee_name,:age,employee_info_attributes:[:id,:city,:address ])
结束
结束


I'm trying to write a nested form in ROR. I have two tables Employee and EmployeeInfo and both table have a column named employeeID these tables are connected with this key. What i want to do is to create a form with some input fields which should update the values into both tables.

for eg i want a form which can create or update fields named employee_name, age, address and city But employee_name and age are present in table Employee and city and address are present in table EmployeeInfo. So how should i write the form tag inorder to do this. Please be sorry if question is a blunder. I'm realy new to this. Pls help

解决方案

Extending @emu's answer

Models setup

#employee.rb
Class Employee < ActiveRecord::Base
  has_one :employe_info
  accepts_nested_attributes_for :employee_info
end

#employee_info.rb
Class EmployeeInfo < ActiveRecord::Base
  belongs_to :employee
end

Controller

Class EmployeesController < ApplicationController

   def new
      @employee = Employee.new
      @employee.build_employee_info
   end

   def create
     @employee = Employee.new(employee_params)

     if @employee.save
     redirect_to @employee
     else
     render 'new'
     end
   end

   private

   def employee_params
     params.require(:employee).permit(:employee_name, :age, employee_info_attributes: [:id, :city,:address])
   end
 end

这篇关于在RoR中编写嵌套表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆