Belajar Ruby on Rails
1. Active Record
Active Record adalah wadah untuk menghubungkan Model dengan database. Di sini, Anda bisa menulis perintah SQL, membuat relasi antar tabel, mengelola value tabel, sampai mengenkripsi data yang bersifat sensitif.
Nah, berikut beberapa syntax dasar Active Record di Ruby on Rails:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | # /membuat active record baru class Product < ApplicationRecord end # /membuat tabel database CREATE TABLE products ( id int( 11 ) NOT NULL auto_increment, name varchar( 255 ), PRIMARY KEY (id) ); # /menginput value ke tabel p = Product. new p.name = "Some Book" puts p.name # "Some Book" |
2. Action Controller
Pada Ruby on Rails, Action Controller berguna untuk mengelola semua fungsi di web. Nah, Anda bisa menghubungkan Model dan View, memproses parameter dan caching, hingga merender template di sini.
Berikut ini beberapa syntax Action Controller pada Ruby on Rails:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | # /membuat method baru class ClientsController < ApplicationController def new end end # /membuat action baru def new @client = Client. new end # /membuat parameter baru class ClientsController < ApplicationController def index if params[ :status ] == "activated" @clients = Client.activated else @clients = Client.inactivated end end def create @client = Client. new (params[ :client ]) if @client .save redirect_to @client else render "new" end end end |
3. Action View
Action View adalah wadah untuk membangun tampilan front end pada Ruby on Rails. Di sini, Anda mengelola template dan menambahkan syntax dari bahasa lain seperti HTML.
Nah, berikut contoh syntax Action View saat belajar pemrograman Ruby on Rails:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | # /menambahkan syntax HTML <h1>Names of all the people</h1> <% @people . each do |person| %> Name: <%= person.name %><br> <% end %> # /menambahkan syntax XML xml.em( "emphasized" ) xml.em { xml.b( "emph & bold" ) } xml.target( "name" => "compile" , "option" => "fast" ) # /menambahkan syntax JSON json.name( "Alex" ) json.email( "alex@example.com" ) |
4. Action Routing
Pada Ruby on Rails, Action Routing berfungsi untuk menghubungkan URL halaman ke Controller. Caranya dengan mengkonfigurasi file resource lewat beberapa perintah seperti index, show, edit, update, dan destroy.
Contoh hasil konfigurasi Action Routing di Rails adalah sebagai berikut:
1 2 3 4 5 6 7 8 9 10 11 | # /membuat konfigurasi routing baru Rails.application.routes.draw do # /menambahkan banyak routing resources :brands , only: [ :index , :show ] do resources :products , only: [ :index , :show ] end # /menambahkan satu routing resource :basket , only: [ :show , :update , :destroy ] end |
Komentar
Posting Komentar