Skip to content

Instantly share code, notes, and snippets.

@maecha
Last active April 3, 2018 06:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maecha/92b42f600a20f0c413e9fad145b3d277 to your computer and use it in GitHub Desktop.
Save maecha/92b42f600a20f0c413e9fad145b3d277 to your computer and use it in GitHub Desktop.
How to use 'Cocoon' | Ruby on Rails 5.1.4 | AdminLTE ver2 (with Bootstrap 3.3.6) | Model 'Hoge' and 'Model 'Fuga' are 'one-to-many relationship'

README

This is the example of using Cocoon.

https://github.com/nathanvda/cocoon

First, You have to edit your Gemfile (as like that), and then, You run this command on CLI, and Cocoon is installed in your Rails project.

$ bundle install

Plz edit anothor files when you've finished up it.

class HogesController < ApplicationController
def new
@hoge = Hoge.new
end
def create
@hoge = Hoge.new(hoge_params)
if @hoge.save
redirect_to root_path,
flash: { success: 'Succeed in creating data.' }
else
flash.now[:alert] = 'Failed in creating data.'
render 'new'
end
end
private
def hoge_params
params.require(:hoge).permit(
:name,
fugas_attributes: [:id, :hoge_id, :name, :_destroy],)
end
end
class Fuga < ApplicationRecord
validates :hoge_id
validates :name
belongs_to :fuga
end
class Hoge < ApplicationRecord
validates :name
has_many :fugas, inverse_of: :hoge, dependent: :destroy
accepts_nested_attributes_for :fugas, reject_if: :all_blank, allow_destroy: true
end
div.nested-fields
div.form-group
= f.label :name
= f.text_field :name,
class: 'form-control',
placeholder: 'Seiya Maeda',
required: true
= link_to_remove_association 'Delete',
f,
class: 'btn btn-box-tool btn-default'
= form_for @hoge, url: hoges_path do |f|
= label_tag 'Fuga Data'
div.form-group
div.fugas-fields-wrapper
= f.fields_for :fugas do |fuga|
= render 'fuga_fields', f: fuga
div.links
= link_to_add_association 'Add',
f,
:fugas,
class: 'btn btn-box-tool btn-default'
gem 'cocoon'
gem 'jquery-rails'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment