LoginSignup
3
2

More than 1 year has passed since last update.

gem cocoon rails6使い方

Last updated at Posted at 2022-08-17

初めに

今回この記事では、gemのcocoonの簡単なチュートリアルを紹介してきます。
この記事ではあくまで簡単なチュートリアルを動かすことを目的として作成しています。
公式のgithubのreadmeではhtmlファイルがhamlで作成されているのでhamlを学習しておらず詰まってしまっている方に向けて作成しています。

github Readme↓
https://github.com/nathanvda/cocoon

上記のreadmeを日本語訳してくれている記事↓
https://note.com/emetselch1984/n/neb1396b86126

実装環境

ruby 3.1.2
rails 6.1.6.1

完成図

Screen_Recording_0004-08-17_at_16_48_12_AdobeExpress.gif

実装

必要なgemやライブラリのインストール

## cocoonはjqueryに依存しているのでjqueryを必須で入れる。

### terminal
$ yarn add jquery
$ yarn add @nathanvda/cocoon
  
### application.jsの中身を書き換える

// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.

import Rails from "@rails/ujs";
import Turbolinks from "turbolinks";
import * as ActiveStorage from "@rails/activestorage";
import "channels";

var jQuery = require("jquery");
global.$ = global.jQuery = jQuery;
window.$ = window.jQuery = jQuery;

require("@nathanvda/cocoon");

Rails.start();
Turbolinks.start();
ActiveStorage.start();

データベースの作成

今回は、公式のreadme通りに実装していきます。

ER図

image.png

## terminal
$ rails g scaffold Project name:string description:string
$ rails g model task description:string done:boolean project:belongs_to

## project.rb ↓を追記
has_many :tasks, inverse_of: :project
accepts_nested_attributes_for :tasks, reject_if: :all_blank, allow_destroy: true

## task.rb ↓を追記
belongs_to :project

## terminal
$ rails db:migrate

formの作成

## _form.html.erb 全て書き換える
<%= form_for @project do |f| %>
 <div class="field">
   <%= f.label :name %>
   <br/>
   <%= f.text_field :name %>
 </div>
 <div class="field">
   <%= f.label :description %>
   <br/>
   <%= f.text_field :description %>
 </div>
 <h3>Tasks</h3>
 <div id='tasks'>
   <%= f.fields_for :tasks do |task| %>
     <%= render 'task_fields', :f => task %>
   <% end %>
   <div class='links'>
     <%= link_to_add_association 'add task', f, :tasks %>
   </div>
 </div>
 <%= f.submit 'Save' %>
<% end %>

## views/projectsの中に_task_fields.html.erbを作成する ↓の内容を全て挿入する

 <div class='nested-fields'>
   <div class="field">
     <%= f.label :description %>
     <%= f.text_field :description %>
   </div>
   <div class="field">
     <%= f.check_box :done %>
     <%= f.label :done %>
   </div>
   <%= link_to_remove_association "remove task", f %>
 </div>

最後に

以上で実装は完了です。
cocoonはレシピサイトの材料や今回のタスク管理など幅広く使うことができそうです。

3
2
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
3
2