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

質問編集履歴

1

中間テーブルを用意し、collection_check_boxesを使いました。

2018/11/08 11:08

投稿

shicchi7913
shicchi7913

スコア6

title CHANGED
File without changes
body CHANGED
@@ -30,6 +30,56 @@
30
30
  end
31
31
  ```
32
32
 
33
+ positionテーブル
34
+ ---
35
+ ```
36
+ class CreatePositions < ActiveRecord::Migration[5.1]
37
+ def change
38
+ create_table :positions do |t|
39
+ t.string :name
40
+
41
+ t.timestamps
42
+ end
43
+ end
44
+ end
45
+ ```
46
+
47
+ 中間テーブルのmember_position
48
+ ---
49
+ ```
50
+ class CreateMemberPositions < ActiveRecord::Migration[5.1]
51
+ def change
52
+ create_table :member_positions do |t|
53
+ t.string :member_id
54
+ t.string :position_id
55
+
56
+ t.timestamps
57
+ end
58
+ end
59
+ end
60
+
61
+ ```
62
+ 各モデルの設定
63
+ ---
64
+ ```
65
+ class Member < ApplicationRecord
66
+ has_many :member_positions
67
+ has_many :positions, through: :member_positions
68
+ accepts_nested_attributes_for :member_positions, allow_destroy: true
69
+ end
70
+
71
+ class Position < ApplicationRecord
72
+ has_many :member_positions
73
+ has_many :members, through: :member_positions
74
+ end
75
+
76
+ class MemberPosition < ApplicationRecord
77
+ belongs_to :member
78
+ belongs_to :position
79
+ end
80
+
81
+ ```
82
+
33
83
  members_controller
34
84
  ---
35
85
  ```
@@ -63,9 +113,8 @@
63
113
  <%= f.label :name, "氏名" %>
64
114
  <%= f.text_field :name %>
65
115
 
66
- <% %w(ピッチャー キャッチャー ファースト セカンド サード ショート レフト センター ライト).each do |position| %>
67
- <%= f.check_box :position, {multiple: true}, value: position %>
116
+ <%= f.collection_check_boxes(:member_positions, Position.all, :id, :name ) do |t| %>
68
- <%= f.label :position, position %>
117
+ <%= t.label { t.check_box + t.name } %>
69
118
  <% end %>
70
119
 
71
120
  <%= f.label :introduction, "選手紹介" %>
@@ -75,6 +124,12 @@
75
124
 
76
125
  <% end %>
77
126
  ```
127
+ position内のデータ
128
+ ---
129
+ ```
130
+ %w[ピッチャー キャッチャー ファースト セカンド サード ショート レフト センター ライト].each { |a| Position.create(name: a) }
131
+ ```
132
+
78
133
  index.html.erb
79
134
  -----
80
135
  ```
@@ -89,11 +144,4 @@
89
144
  <% end %>
90
145
  ```
91
146
 
92
- なのですが、実際の表示になると、
93
- ```index
94
- 氏名:田中太郎
95
- ポジション: ["0", "{:value=>\"ピッチャー\"}", "0", "{:value=>\"キャッチャー\"}", "0", "0", "0", "0", "0", "0", "0"]
96
- 紹介文:○○○○○○○○
97
- ```
98
- となってしまいます。
99
147
  よろしくお願いいたします。