2016年10月17日 星期一

Cloud9-RoR-one-to-many & create multiple records at once

參考文章:http://vicfriedman.github.io/blog/2015/07/18/create-multiple-objects-from-single-form-in-rails/
rails儲存的方法區別:http://rubyer.me/blog/262/

這次的功能需求是一次能夠存取多筆資料,且剛好是符合一對多的資料型態,先從一對多(user-to-calendars)的設定開始吧!

One-to-Many
User(one),編輯 app/models 底下的 user.rb 檔,加入
  has_many :calendars, :dependent => :delete_all

Calendars(many),一樣編輯 models 下的 calendar.rb,加入
  belongs_to :user

可以注意到 has_many 字尾有{s}(複數), belongs_to 是沒有的(單數)。


Create Multiple Records at Once
編輯calendar_controller.rb
  def new
    @calendar = []
    20.times do
      @calendar << calendar.new
    end
  end

  def create
    if params.has_key?("calendar")
      @calendar = calendar.create(calendar_params(params["calendar"]))
    else
      params["calendars"].each do |calendar|
        if calendar["issave"] && calendar["vdate"] != ""
          @calendar = calendar.create(calendar_params(calendar))
        end
      end
    end

    if @calendar.save
      redirect_to calendars_url
    else
      render :action => :new
    end
    flash[:notice] = "calendar was successfully created"
  end

編輯views/calendars/new.html.erb
<%= form_tag calendars_path do %>
  <% i=0 %>
  <table border="0">
    <tr>
      <td>儲存</td>
      <td>日期</td>
      <td>時間</td>
    </tr>
  <% @calendar.each do |calendar| %>
    <%= fields_for 'calendars[]', calendar do |f| %>
      <tr>
        <td>
        <div>
        <% if i < 1 %>
        <%= hidden_field_tag('calendars[][issave]', true) %>
        <% else %>
        <%= check_box_tag('calendars[][issave]', true) %>
        <% end %>
        <%= f.hidden_field :user_id, :value => current_user.id %>
        </div>
        </td>
        <td>
        <div>
        <%= f.date_field :vdate %>
        </div>
        </td>
        <td>
        <div>
        <%= f.select(:vtime) do %>
          <% (0..23).each do |t| -%>
            <%= content_tag(:option, t.to_s.rjust(2, '0'), value: t) %>
          <% end %>
        <% end %>
        </div>
        </td>
      <% i=i+1 %>
    <% end %>
    </tr>
  <% end %>
  </table>
  <div class="actions">
    <%= submit_tag %>
  </div>
<% end %>

執行後的畫面

完成後在日曆上看不到資料是正常的哦!因為我們還沒將資料套用到日曆上,下一篇就會介紹如何使用json將資料顯示在fullcalendar上哩!

2016年10月16日 星期日

CoffeeScript

記錄一下CoffeeScript的資源。

撰寫coffeescript時,縮排非常重要,它是靠縮排來判斷程式碼間的層級關係。

官網:http://coffeescript.org/
  • TABLE OF CONTENTS:範例 
  • TRY COFFEESCRIPT:CoffeeScript→Javascript
  • ANNOTATED SOURCE:源始碼

Javascript→CoffeeScript:http://js2.coffee/
將Javascript轉為CoffeeScript的寫法,對於初學者來說很有幫助。

2016年10月10日 星期一

Cloud9-RoR-fullcalendar-rails 安裝

參考來源:https://rubygems.org/gems/fullcalendar-rails/versions
參考文章/下載來源:https://github.com/bokmann/fullcalendar-rails
官網:https://fullcalendar.io/
doc說明:https://fullcalendar.io/docs/
範例參考(1):http://vinsol.com/fullcalendar-demo
範例參考(1)下載來源:https://github.com/vinsol/fullcalendar_rails
範例參考(2):http://blog.crowdint.com/2014/02/18/fancy-calendars-for-your-web-application-with-fullcalendar.html
輔助套件(必裝):https://github.com/derekprior/momentjs-rails

p.s.範例參考都有提供GitHub下載,可以用clould9另開一個新專案載入後試玩看看。

fullcalendar-rails需要用到momentjs-rails,所以我們先安裝monentjs-rails套件。如果想先檢查有沒有相關套件,可以執行以下指令:
$ gem list
底下會列出主機上所有安裝的gem套件,已經安裝的人可以跳過安裝步驟哦。

momentjs-rails
執行安裝指令
$ gem install momentjs-rails
$ bundle install

在Gemfile檔加上兩行
# momentjs
gem 'momentjs-rails'

編輯application.js檔,加入
//= require moment 

編輯test/test_helper.rb檔,加入
  test "truth" do
    assert_kind_of Module, Momentjs::Rails
  end

然後上傳下列的檔案到指定的資料夾中
  • lib:momentjs-rails.rb
  • vendor\assets\javascripts:moment.js、moment folder

fullcalendar-rails
執行安裝指令
$ gem install fullcalendar-rails
$ bundle install

在Gemfile檔加上兩行
# full calendar
gem 'fullcalendar-rails'

編輯application.css檔,加入
 *= require fullcalendar

編輯application.js檔,加入
//= require fullcalendar

如果想要轉換語系,再加入
//= require fullcalendar/lang/zh-tw

接下來有兩種套用方式,model跟view。

model:在app\assets\javascripts\找到該mode的.coffee檔,加入
$(document).ready ->
  $("#calendar").fullCalendar(
    lang: 'zh-tw' #轉換語系
    editable: true
    header:
      left: 'prev,next today'
      center: 'title'
      right: 'month,agendaWeek,agendaDay,listWeek'
    defaultView: 'month'
    height: 500
    slotMinutes: 15
  )

打開該model下的view(.html.erb)檔,再加入
<div id="calendar"></div>
就會顯示月曆了。

view:想套用單一頁面則打開該view(.html.erb)檔後,加入
<scrip>
$(document).ready(function(){
  $('#calendar').fullCalendar({
    lang: 'zh-tw', //轉換語系
    editable: true,
    header: {
      left: 'prev,next today',
      center: 'title',
      right: 'month,agendaWeek,agendaDay,listWeek'
    },
    defaultView: 'month',
    height: 500,
    slotMinutes: 15
  });
});
</scrip>

<div id="calendar"></div>

從這段起跟列印有關,不需要用到列印功能的人可以跳過。
----------------------------------------------------------------------------------
在stylesheets資料夾下新增一個application-print.css.scss檔。

編輯config/application.rb檔,加上
config.assets.precompile += ['application-print.css']

在需要列印的view頁面加入
<%= stylesheet_link_tag "application-print", :media => "print" %>
----------------------------------------------------------------------------------

上傳下列檔案
  • lib:fullcalendar-rails.rb及fullcalendar-rails folder
  • vendor\assets\javascripts:fullcalendar folder、fullcalendar.js
  • vendor\assets\stylesheets:fullcalendar.css、fullcalendar.print.css
希望大家都能順利的完成嘍!

2016年9月21日 星期三

PHP MVC laravel 學習過程記錄

因為最近接的案子業主對於PHP較有研究,於是決定重操舊業回頭學習PHP的MVC架構,不過為了讓環境單純化,所以這次是使用VMware Player來架設,這篇文章主要是來紀錄從架設到寫程式的過程,應該就只是單純的做剪剪貼貼,畢竟網路上已經有很多相關的教學文章,這篇只是把參考過的文章記錄下來而已。
  1. VMware Player:因為我的環境是Windows7 32-bit,但官網目前已經更新到64-bit,所以花了一段時間找檔案,如果你是64-bit的話,直接到官網下載最新版就行了。
    32-bit
    64-bit
  2. Windows 7 ISO檔:微軟有提供載點,只是要先輸入序號驗證。
  3. laravel-Windows:這個教學網是直接使用XAMPP的套裝軟體,能夠迅速的把PHP、MySQL及Apache安裝好。
    很重要!很重要!很重要!請下載PHP7的版本,PHP7在效能上提升很多,既然要用了當然要選最優的嘍!
  4. Sublime Text 3:這次選擇的編輯器,是說我也是第一次使用,請安裝Sublime Text 3的版本,完成後可以參考此篇(如果你是安裝laravel5,文章最下方安裝 Generators的部份請不要跟著做,該篇文章內所使用的Generators版本還不支援laravel5,想要使用該套件的話可以參考這篇來安裝Generators套件)裡面有介紹相關的laravel外掛。(請注意自己安裝的laravel版本,文章裡是4,但我是安裝5,所以在安裝時記得依據自己的版本來選擇)
  5. Laravel 5.3 預熱:介紹laravel5.3改變了哪些東西。
  6. 目錄及指令介紹laravel目錄及一些常用的指令,不過目錄介紹是針對舊版的laravel為主唷。
  7. php artisan指令:尚未實作,後續補上。
  8. Laravel官網:實作檔案的修改前先看看這篇吧!
  9. Laravel基本設定:安裝完laravel後需要更改的一些設定,不過此篇的寫法是屬於舊版本的寫法,檔案目錄的位置也不一樣了,修改記錄如下,我目前只做到routes的設定哦!
    文章路徑實際路徑修改內容
    app/config/app.phpconfig/app.php'timezone' => 'Asia/Taipei' 'debug' => env('APP_DEBUG', true),
    app/config/database.phpconfig/database.php 暫不修改
    app/routes.phproutes/web.phpRoute::get('/index.html', function() { return View::make('welcome'); });

2016年8月3日 星期三

Cloud9-RoR-link_to

參考來源:http://stackoverflow.com/questions/2124862/link-to-send-parameters-along-with-the-url-and-grab-them-on-target-page
詳細文章:http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to
參考文章:http://apidock.com/rails/v3.2.8/ActionView/Helpers/UrlHelper/link_to

link_to需要傳值時的寫法
<%= link_to "連結", products_path(:param1 => "value1", :param2 => "value2"), class: "color1" %>

link_to連結文字內容較複雜時的寫法
<%= link_to(product) do %>
  <img src="images/<%= product.image_url %>" class="img-responsive" alt=""/>
  <h3><%= product.title %></h3>
  <h4>$<%= product.price %></h4>
<% end %>

此篇將會不定期的更新哦!

2016年7月29日 星期五

Cloud9-RoR-Authentication:devise validate custom fields and rails-i18n

參考文章:https://ihower.tw/rails4/i18n.html
詳細介紹-validate:http://guides.rubyonrails.org/active_record_validations.html
詳細介紹-自訂警語:http://guides.rubyonrails.org/i18n.html#translations-for-active-record-models
參考來源:http://stackoverflow.com/questions/808547/fully-custom-validation-error-message-with-rails
參考文章:http://ricostacruz.com/cheatsheets/rails-i18n.html
下載 rails-i18n:https://github.com/svenfuchs/rails-i18n 

上一篇是介紹如何新增自訂欄位,這一篇就來教大家怎麼增加自訂欄位的驗證,雖然只有短短幾行,卻花費了我好多時間…總之,在打算放棄devise時,讓我找到了解答,還好最後還是守住了,神啊~讓我之後順利點吧!

打開app/models/user.rb檔,加入我們想要驗證的欄位名稱
  validates :cname, presence: true
  validates :phone1, numericality: true, length: { in: 9..12 }
  validates :zipcode, numericality: { only_integer: true }, length: { in: 3..5 }
  validates :address, presence: true

編輯Gemfile,加上
# 語系檔
gem "rails-i18n"

執行指令
$ gem install rails-i18n

在config/locales/下新增一個zh-TW.yml的檔案,用來指定各欄位顯示的文字,models用來指定rails/locale/底下的%{resource}名稱。
zh-TW:
  activerecord:
    models:
      user: "會員資料"
    attributes:
      user:
        cname: "姓名"
        email: "信箱"
        phone1: "電話1"
        zipcode: "郵遞區號"
        address: "地址"
        password: "密碼"
        password_confirmation: "確認密碼"

編輯config/application.rb
    # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
    config.i18n.load_path += Dir[Rails.root.join('rails', 'locale', '*.{rb,yml}').to_s]
    config.i18n.default_locale = "zh-TW"

    #devise_error
    config.action_view.field_error_proc = Proc.new { |html_tag, instance| 
      "<font style=\"color: #CC0000;\">#{html_tag}</font>".html_safe
    }

因為我發現 install 後檔案還是沒出現,可能要自行放上吧,如果你也是,就把下載 rails-i18n的檔案放到專案中,不過…我並沒有全放就是了,我放上的檔案如下:
  • bin/i18n-tasks, rspec
  • config/i18n-tasks.yml
  • lib (all)
  • rails (all)
  • space (all)
  • rails-i18n.gemspec
  • locales.thor
編輯 rails/locale/zh-TW.yml,把%{model}的部份取代為%{resource},並加上下列程式碼(綠色部份)
  errors:
    format: "%{attribute} %{message}"
      messages:
        not_saved:
          one: 有 1 個錯誤發生使得「%{resource}」無法被儲存。
          other: 有 %{count} 個錯誤發生使得「%{resource}」無法被儲存。

執行程式,連結到註冊頁面,按下SIGN UP鈕就可以看到下圖的警告視窗。











欄位文字的部份則會變成粗體紅字。









希望大家也能順利完成,本篇就到此結束,終於…寫了好幾個星期…

2016年7月12日 星期二

Cloud9-RoR-Authentication:devise add fields

參考文章:http://jacopretorius.net/2014/03/adding-custom-fields-to-your-devise-user-model-in-rails-4.html

如果想要在devise套件裡增加欄位該怎麼做呢?create the migrationd可以看此篇有關users的部份,以下就直接跳到create controller的步驟嘍!

首先,先新增一個RegistrationsController
$ rails g controller registrations

打開registrations_controller.rb檔,編輯內容,注意class的地方不一樣,有做繼承devise的動作
#class RegistrationsController < ApplicationController
class RegistrationsController < Devise::RegistrationsController  
  private

  def sign_up_params
    params.require(:user).permit(:cname, :phone1, :phone2, :address, :zipcode, :email, :password, :password_confirmation)
  end

  def account_update_params
    params.require(:user).permit(:cname, :phone1, :phone2, :address, :zipcode, :email, :password, :password_confirmation, :current_password)
  end
end

修改config/routes.rb
  #devise_for :users
  devise_for :users, :controllers => { registrations: 'registrations' }

Done.