質問するログイン新規登録

質問編集履歴

3

説明補足

2017/03/14 07:37

投稿

pecchan
pecchan

スコア592

title CHANGED
File without changes
body CHANGED
@@ -1,3 +1,10 @@
1
+ 社員の新規登録時に、同じ画面で
2
+ 資格も複数行登録したいです。
3
+
4
+ 親:社員
5
+ 子:資格
6
+
7
+
1
8
  色々と参考にしながら、accepts_nested_attributes_forを使い
2
9
  親子関係のモデルを同時に登録するところまで出来ました。
3
10
 
@@ -11,19 +18,14 @@
11
18
  受注伝票キーは自動でセットされますが
12
19
  受注伝票番号も同じタイミングでセットしたい場合です。
13
20
 
21
+ 今回の場合ですと、
22
+ viewで入力された社員名(emp_name)を
23
+ 子のemp_nameにもセットして登録したいです。
14
24
 
15
25
  宜しくお願い致します。
16
26
 
17
- 親:社員
18
- 子:資格
19
27
 
20
- 社員の新規登録時に、同じ画面で
21
- 資格も複数行登録したいです。
22
28
 
23
- viewで入力された社員名(emp_name)を
24
- 子のemp_nameにもセットして登録したいです。
25
-
26
-
27
29
  社員モデル
28
30
  ```ruby
29
31
  class Employee < ApplicationRecord

2

2017/03/14 07:37

投稿

pecchan
pecchan

スコア592

title CHANGED
File without changes
body CHANGED
@@ -17,7 +17,13 @@
17
17
  親:社員
18
18
  子:資格
19
19
 
20
+ 社員の新規登録時に、同じ画面で
21
+ 資格も複数行登録したいです。
20
22
 
23
+ viewで入力された社員名(emp_name)を
24
+ 子のemp_nameにもセットして登録したいです。
25
+
26
+
21
27
  社員モデル
22
28
  ```ruby
23
29
  class Employee < ApplicationRecord

1

ソース追加

2017/03/14 07:34

投稿

pecchan
pecchan

スコア592

title CHANGED
File without changes
body CHANGED
@@ -12,4 +12,63 @@
12
12
  受注伝票番号も同じタイミングでセットしたい場合です。
13
13
 
14
14
 
15
- 宜しくお願い致します。
15
+ 宜しくお願い致します。
16
+
17
+ 親:社員
18
+ 子:資格
19
+
20
+
21
+ 社員モデル
22
+ ```ruby
23
+ class Employee < ApplicationRecord
24
+
25
+ has_many :license, dependent: :delete_all
26
+
27
+ accepts_nested_attributes_for :license, allow_destroy: true
28
+
29
+ validates :emp_name, presence: true
30
+ end
31
+
32
+ ```
33
+
34
+
35
+ 社員コントローラ
36
+ ```ruby
37
+ class EmployeesController < ApplicationController
38
+ before_action :set_employee, only: [:show, :edit, :update, :destroy]
39
+
40
+ # POST /employees
41
+ # POST /employees.json
42
+ def create
43
+ @employee = Employee.new(employee_params)
44
+
45
+
46
+ respond_to do |format|
47
+ if @employee.save
48
+ format.html { redirect_to @employee, notice: 'Employee was successfully created.' }
49
+ format.json { render :show, status: :created, location: @employee }
50
+ else
51
+ format.html { render :new }
52
+ format.json { render json: @employee.errors, status: :unprocessable_entity }
53
+ end
54
+ end
55
+ end
56
+
57
+
58
+ private
59
+ # Use callbacks to share common setup or constraints between actions.
60
+ def set_employee
61
+ @employee = Employee.find(params[:id])
62
+ end
63
+
64
+ # Never trust parameters from the scary internet, only allow the white list through.
65
+ def employee_params
66
+ params.require(:employee).permit(
67
+ :emp_code,
68
+ :emp_name,
69
+ :retire_date,
70
+ lisence_attributes:[:id, :emp_code, :emp_name, :_destroy])
71
+ end
72
+ end
73
+
74
+ ```