37
37

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

simple_formで動的にフォーム要素を追加・削除する

Posted at

#やりたいこと

simple_formを使っていて、ネストされたフォームを動的に追加、削除したい

解決方法

nested_formを使う。

使用方法

Gemfileに記入して bundle

Gemfile
gem 'nested_form'

application.jsに追加

application.js

//= require jquery_nested_form

simple_nested_form_forでフォームを作成する

要素を追加する場合、 link_to_addで指定する。その際、data: { target: '#tasks' } を指定することで、idがtasksのところに追加されていく。

要素を削除する場合は、link_to_removeで削除することが可能。

<%= simple_nested_form_for @post do |m| %>
	<%= m.input :title, label: 'タイトル' %>
		<table id='tasks'>
			<%= m.simple_fields_for :steps do |s| %>
				<tr class='steps-field'>
					<td>
						<%= s.text_area :content' %>
					</td>
					<td>
						<%= s.link_to_remove '削除' %>
					</td>
				</tr>
			<% end %>
		</table>
		<%= m.submit %>
		<%= m.link_to_add "追加", :steps, data: { target: '#tasks'} %>
<% end %>

参考

37
37
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
37
37

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?