質問編集履歴

2

コードを追記しました

2019/08/26 08:00

投稿

taroo
taroo

スコア5

test CHANGED
File without changes
test CHANGED
@@ -111,3 +111,37 @@
111
111
  });
112
112
 
113
113
  ```
114
+
115
+
116
+
117
+ index.html.erb(投稿フォーム)
118
+
119
+ ```
120
+
121
+ <%= form_for [@group, @post],id: :new__post, html: {id:'new-post'} do |f| %>
122
+
123
+ <div class="form">
124
+
125
+ <div class="form-body">
126
+
127
+ <div class="post-form">
128
+
129
+ </div>
130
+
131
+ <textarea class="textbox", name="post[content]", id="input-text"></textarea>
132
+
133
+ <div class="form__mask">
134
+
135
+ <div>
136
+
137
+ <input type="submit" name="commit" value="投稿" data-disable-with="投稿" class="form__submit">
138
+
139
+ </div>
140
+
141
+ </div>
142
+
143
+ </div>
144
+
145
+ <% end %>
146
+
147
+ ```

1

コード追記

2019/08/26 08:00

投稿

taroo
taroo

スコア5

test CHANGED
File without changes
test CHANGED
@@ -15,3 +15,99 @@
15
15
 
16
16
 
17
17
  よろしくお願いします。
18
+
19
+
20
+
21
+ コード
22
+
23
+ postsモデル
24
+
25
+ ```
26
+
27
+ validates :content, presence: true, length: { minimum: 50 }
28
+
29
+ ```
30
+
31
+
32
+
33
+ posts.js
34
+
35
+ ```
36
+
37
+ $(function() {
38
+
39
+ function buildHTML(post){
40
+
41
+ var html = `<div class="post" data-id=${post.id}>
42
+
43
+ <div class="upper-post"
44
+
45
+ <div class="upper-post__date">
46
+
47
+ ${post.created_at}
48
+
49
+ </div>
50
+
51
+ <div class="lower-post__content">
52
+
53
+ ${post.content}
54
+
55
+ </div>
56
+
57
+ </div>
58
+
59
+ </div>`
60
+
61
+ return html
62
+
63
+ }
64
+
65
+
66
+
67
+ $('#new-post').on('submit', function(e) {
68
+
69
+ e.preventDefault();
70
+
71
+ var formData = new FormData(this);
72
+
73
+ var url = $(this).attr('action')
74
+
75
+ $.ajax({
76
+
77
+ url: url,
78
+
79
+ type: "POST",
80
+
81
+ data: formData,
82
+
83
+ dataType: 'json',
84
+
85
+ processData: false,
86
+
87
+ contentType: false
88
+
89
+ })
90
+
91
+ .done(function(post){
92
+
93
+ var html = buildHTML(post);
94
+
95
+ $('.form__submit').attr('disabled', false);
96
+
97
+ $('.posts').prepend(html);
98
+
99
+ $('#new-post')[0].reset();
100
+
101
+ })
102
+
103
+ .fail(function(){
104
+
105
+ alert('投稿に失敗しました');
106
+
107
+ })
108
+
109
+ })
110
+
111
+ });
112
+
113
+ ```