iT邦幫忙

DAY 11
3

Rails. Really, I love study.系列 第 11

新生。

  • 分享至 

  • xImage
  •  

"萬物渾沌,始於新生"

該如何增加一筆資料呢?
來作出可以增加一筆資料的功能吧

先刻好要輸入資料的畫面

app/views/girbs/new.html.erb


<div class="container">
<%= form_for @girb, :html => {:class => "form-horizontal center"} do |f| %>
<div class="form-group">
<%= f.label :name, "Name:", class: "col-md-3 control-label" %>
<div class="col-md-7">
<%= f.text_field :name, class: "form-control" %>
</div>
</div>
<div class="form-group">
<%= f.label :email, "Email:", class: "col-md-3 control-label" %>
<div class="col-md-7">
<%= f.text_field :email, class: "form-control" %>
</div>
</div>
<div class="form-group">
<%= f.label :like, "Like:", class: "col-md-3 control-label" %>
<div class="col-md-7">
<%= f.text_area :like, class: "form-control" %>
</div>
</div>
<div class="form-group">
<div class="col-md-3 control-label">
</div>
<div class="col-md-7">
<%= f.submit "Submit", class: "btn btn-default btn-primary" %>
</div>
</div> 
<% end %>
</div>

接下來寫出個按鈕可以叫出新增的畫面
這邊用了兩種不同寫法,但功能作用是一樣的

app/views/layouts/application.html.erb

....

<!-- start of footer -->
<div class = "navbar navbar-default navbar-fixed-bottom">
<div class = "container">
<sapn class = "navbar-text">Site Built By Hazetodo </span>
<%= link_to "Bilink", girbs_path, :class => "navbar-btn btn-danger btn btn-sm" %>
<%= link_to new_girb_path, :class => "navbar-btn btn btn-primary btn-sm " do %>
<i class=" fa fa-plus fa-sm"></i> New
<% end %>
<%= link_to raw('<i class="fa fa-plus fa-sm"></i> New'), new_girb_path, :class => "navbar-btn btn btn-warning btn-sm" %>
</div>
</div>
<!-- end of footer -->

再去寫相對應的 controller

app/controllers/girbs_controller.rb

class GirbsController < ApplicationController
def index
@girbs = Girb.all
end

def like
@girb = Girb.find(params[:id])
@girb.like += 1;
@girb.save
redirect_to(girbs_path)
end

def on_click_bang
@girb = Girb.find(params[:id])
@girb.bangs.create
redirect_to(girbs_path)
end

def new
@girb = Girb.new
end
def create
@girb = Girb.new(girb_params)
if @girb.save
redirect_to(girbs_path)
else
render :new
end
end

private

def girb_params
params.require(:girb).permit(:name, :email, :like)
end
end

紅色按鈕 Bilink 是回到首頁
藍色按鈕 +New 會跳到新增資料頁面
黃色按鈕 +New 會跳到新增資料頁面


上一篇
化妝。
下一篇
顯現。
系列文
Rails. Really, I love study.30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言