12/08/2018, 14:53

Demo Multi Select Drop Down with Ruby on Rails

rails new demo > cd demo > rails g scaffold book name:string > rails g scaffold author name:string > rails g model authorbook author_id:integer book_id:integer class CreateAuthors < ActiveRecord::Migration def change create_table :authors do |t| t.string ...

rails new demo
> cd demo
> rails g scaffold book name:string
> rails g scaffold author name:string
> rails g model authorbook author_id:integer book_id:integer 
class CreateAuthors < ActiveRecord::Migration
  def change
    create_table :authors do |t|
      t.string :name

      t.timestamps null: false
    end
  end
end
class CreateBooks < ActiveRecord::Migration
  def change
    create_table :books do |t|
      t.string :name

      t.timestamps null: false
    end
  end
end

class CreateAuthorbooks < ActiveRecord::Migration
  def change
    create_table :authorbooks do |t|
      t.references :author, index: true, foreign_key: true
      t.references :book, index: true, foreign_key: true

      t.timestamps null: false
    end
  end
end
> rake db:migrate

Khai báo mối quan hệ cho các model :

class Author < ActiveRecord::Base
  validates :name, presence: true 

  has_many :authorbooks
  has_many :books, through: :authorbooks
end
class Authorbook < ActiveRecord::Base
  belongs_to :author
  belongs_to :book
end
class Book < ActiveRecord::Base
  validates :name, presence: true

  has_many :authorbooks
  has_many :authors, through: :authorbooks
end

Nhúng semantic vào hỗ trợ giao diện:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/1.11.8/semantic.min.css"/>

<%= javascript_include_tag "https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.4/semantic.min.js", 'data-turbolinks-track' => true %>

File dropdown.js

$(document).on('turbolinks:load', function() {
    $('.ui.dropdown').dropdown();
});

Khai báo trong controller

class AuthorsController < ApplicationController
  before_action :set_author, only: [:show, :edit, :update, :destroy]

  # GET /authors
  # GET /authors.json
  def index
    @authors = Author.all
  end

  # GET /authors/1
  # GET /authors/1.json
  def show
    @author_book = @author.authorbooks
  end

  # GET /authors/new
  def new
    @author = Author.new
    get_books
  end

  # GET /authors/1/edit
  def edit
    get_books
  end

  # POST /authors
  # POST /authors.json
  def create
    @author = Author.new(author_params)
    params[:books][:id].each do |book|
      if !book.empty?
        @author.authorbooks.build(:book_id => book)
      end
    end

    respond_to do |format|
      if @author.save
        format.html { redirect_to @author, notice: 'Author was successfully created.' }
        format.json { render :show, status: :created, location: @author }
      else
        format.html { render :new }
        format.json { render json: @author.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /authors/1
  # PATCH/PUT /authors/1.json
  def update
    respond_to do |format|
      if @author.update(author_params)
        # http://guides.rubyonrails.org/association_basics.html
        @author.books = []
        params[:books][:id].each do |book|
          if !book.empty?
            @author.books << Book.find(book)
          end
        end
        format.html { redirect_to @author, notice: 'Author was successfully updated.' }
        format.json { render :show, status: :ok, location: @author }
      else
        format.html { render :edit }
        format.json { render json: @author.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /authors/1
  # DELETE /authors/1.json
  def destroy
    @author.destroy
    respond_to do |format|
      format.html { redirect_to authors_url, notice: 'Author was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_author
      @author = Author.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def author_params
      params.require(:author).permit(:name)
    end

    # Utility methods
    def get_books
      @all_books = Book.all
      @author_book = @author.authorbooks.build
    end
end

File authors/_form.html.erb

<%= javascript_include_tag "dropdown.js" %>
<%= form_for(@author) do |f| %>
  <% if @author.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@author.errors.count, "error") %> prohibited this author from being saved:</h2>

      <ul>
      <% @author.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>

  <%= fields_for(@author_book) do |ab| %>
    <div class="field">
      <%= ab.label "All Books" %><br/>
      <%= collection_select(:books, :id, @all_books, :id, :name, {}, {:multiple => true, class: "ui fluid  selection dropdown", id: "select-book"}) %>
    </div>
  <% end %>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

Source code:

0