跳到主要內容

發表文章

目前顯示的是 2018的文章

How to attach a file/image in your data? Using paperclip in a rails application.

在 rails 裡有一個很好用的夾檔套件paperclip,今天就要來簡單介紹paperclip怎麼用. 首先要利用imagemagick套件,讓你的rails專案具有處理影像的能力. Mac OS X $ brew install imagemagick  Linux distribution $ sudo apt-get install imagemagick -y 然後在Gemfile中引用paperclip. # Gemfile ... gem "paperclip", git: "git://github.com/thoughtbot/paperclip.git" ... 記得bundle一下. $ bundle install 接下來利用scaffold製作一個範例,在這個範例中我們要用paperclip幫這個使用者加上照片,paperclip會將照片資料記錄起來並將照片上傳到public資料夾內. $ rails generate scaffold User name:string email:string tel:string  生成附檔資料表 $ rails generate paperclip user avatar 修改 class AddAvatarToUsers < ActiveRecord::Migration[5.2]   def up    add_attachment :users, :avatar   end   def down    remove_attachment :users, :avatar   end end 讓user model知道怎麼處理夾檔,可以上傳的檔案格式容量限制等都可以寫在這裡. # app/models/user.rb  class User < ActiveRecord::Base  has_attached_file :avatar, styles: { medium: "300x300", thumb: "100x100" }   validates_attachment_content_t

undefined method `for' for #<' Devise::ParameterSanitizer:0x00007f0e320f79d0 '>

 NoMethodError in Devise::RegistrationsController#edit 用Devise套件作為系統的帳號管理功能,結果在這個檔案出現錯誤. app/controller/application_controller.rb class ApplicationController < ActionController::Base   # Prevent CSRF attacks by raising an exception.   # For APIs, you may want to use :null_session instead.   protect_from_forgery with: :exception   before_action :configure_permitted_parameters , if: :devise_controller ?   protected   def configure_permitted_parameters     devise_parameter_sanitizer . for ( :sign_up ) { | u | u.permit( :username , :email , :password , :password_confirmation , :remember_me , :avatar , :avatar_cache ) }     devise_parameter_sanitizer . for ( :account_update ) { | u | u.permit( :username , :password , :password_confirmation , :current_password , :avatar ) }   end end   只要將for修正成permit,就可以了. def configure_permitted_parameters    devise_parameter_sanitizer .permit ( :sign_up )  {... }   devise_parameter_sanitizer .permit ( :account_update )  {... } end

How to use docker compose build a ruby on rails container?

在推Ruby on rails協同開發架構時,發現每個人的電腦都不同,有的是windows、有的是linux、有的則是mac,單單為了要讓大家能一起開始,就傷透腦筋,為了解決開發環境一致性的問題,我們採用了docker,想法是:如果有一個能跨越自身的電腦作業系統版本,大家都能共用的環境,如同VM,我們不就可以解決這個問題了;所以有了這個專案。 Github網址: https://github.com/tyRoRteam/dev_docker 如何使用 安裝docker 請先到 Docker官網  安裝適合電腦的版本, 使用windows的朋友需注意必須windows 10 professional版本才裝得起來。 Download git repo $ git clone https://github.com/tyRoRteam/dev_docker.git  Build and Run RoR development docker container $ cd dev_docker $ docker-compose up -d  Login to container  $ ssh -X -p 10022 user@localhost (default username/password: user/user) docker-compose.yml 設定檔 version: '3'  services:  ror_dev:   build: ror_dev/   ports:    - "10022:22"    - "10080:3000"   volumes:    - ./user_home:/home/user    - ./configs/sshd_config:/etc/ssh/sshd_config 在設定檔中,我們開通了本機與container兩個port對接,本機的10022連接container的22 port,讓ssh可以連得進去,另一個就是本機的10080連接container的3000 port,因為rails s預設為3000 port,這樣當container內執行 $ rails s 時,就可以用本機瀏覽器 ht

How to maintain your project source code in GitHub with collaborative development?

一個人的江湖很孤獨 一個人的江湖是孤獨的,寫程式也是,雖然很多高手都是一個人,但是如果能集合多人的力量不是更好嗎?高手難求,但是一個好的團隊卻是可以培養出來的,加入一個好的團隊,大家努力往前爬,不也是一種幸福嗎? 所以,這篇文章就是要說明如何與團隊協同開發系統,協同開發的流程會是怎麼樣子來進行呢? 組織( Organization) 開發團隊或稱為專案團隊,可以視為一個組織,在組織中有許多角色,有專案管理者、程式開發人員.....等,在GitHub中將專案管理者視為專案擁有者(Owner),其他專案開發者(Member),下圖描述說明:組織(organization)名稱為Org X,其中Mark為專案管理者(owner)、Jimmy與Bill都是程式開發人員(member)。 在這個組織中主要維運一個專案(repo_abc),為Jimmy,Bill和Mark共同維護,接下來就以Jimmy觀點來看他怎麼進行維護專案. Step1) 同步 當有需求需要進行程式修改時,先要進行程式碼同步,把OrgX上repo_abc/master最新程式碼抓下來. $ git fetch remote: Enumerating objects: 9, done. remote: Counting objects: 100% (9/9), done. remote: Compressing objects: 100% (4/4), done. remote: Total 5 (delta 2), reused 3 (delta 1), pack-reused 0 Unpacking objects: 100% (5/5), done. From https://github.com/Org_x/repo_abc e795431..d4468d5 master -> origin/master Step2) 同步再上傳 當完成修改準備要push程式碼到Jimmy的GitHub/repo_abc時,記得先再同步一次,確定沒問題再push. $ git add . $ git commit -m "mark PENDING: Not yet implemented&quo

Gradle sync failed: Failed to find Build Tools revision 26.0.2

新建立的Android app專案發生下面錯誤,怎麼解決? Gradle sync failed: Failed to find Build Tools revision 26.0.2 這是因為Gradle版本不支援的關係,所以就讓點選錯誤提示下面的連結啟動安裝/更新就可以。

Gradle sync failed: Could not determine java version from '9.0.1'.

新建立的Android app專案發生下面錯誤,怎麼解決? Gradle sync failed: Could not determine java version from '9.0.1'. 這是因為找不到java path的關係,所以就讓專案知道路徑就可以。 (File -> Project Structure -> Project) JDK location: 把Use embedded JDK(recommended)打勾 /Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk/Contents/Home

建立自己第一個gem

1. 先要有https://rubygems.org/帳號 2. 安裝環境必要套件 $ gem update --system $ gem install rubygems-update Fetching: rubygems-update-2.7.6.gem (100%) Successfully installed rubygems-update-2.7.6 Parsing documentation for rubygems-update-2.7.6 Installing ri documentation for rubygems-update-2.7.6 Done installing documentation for rubygems-update after 28 seconds 1 gem installed $ update_rubygems 3. 建立gem資料夾 (voteable_shawn) $mkdir voteable_shawn $cd voteable_shawn $mkdir lib 4. 設定檔 voteable_shawn/voteable_shawn.gemspec Gem::Specification.new do |s|   s.name        = 'voteable_shawn'   s.version     = '0.0.0'   s.licenses    = ['MIT']   s.summary     = "This is a voteable gem example!"   s.description = "The voting gem!"   s.authors     = ["Shawn"]   s.email       = 'shawnkuo67@gmail.com'   s.files       = ["lib/voteable_shawn.rb"]   s.homepage    = 'https://rubygems.org/gems/example'  

解決Ruby升級後發生的has_many NoMethodError: undefined method `name' for nil:NilClass問題

rvm 2.1.4跑起來正常的專案,升級rvm 2.2.2就噴下面錯誤訊息要怎麼修正它呢? https://github.com/shawnkaku/postit-solution.git 補充:下載後要先bundle update json sqlite3 感謝網友 蔡鴻銘 指導 https://github.com/....../active_scaffold/issues/380...... 升級到rails 4.1.16 + ruby 2.2.4 問題就消失了 Step 1:安裝rvm 2.2.4 $ rvm install 2.2.4 $ rvm use 2.2.4 Using /Users/shawnkuo/.rvm/gems/ruby-2.2.4 Step 2: 修改Gemfile source 'https://rubygems.org' ruby '2.2.4' gem 'rails', '4.1.16' Step 3:升級專案套件 $ ruby -v ruby 2.2.4p230 (2015-12-16 revision 53155) [x86_64-darwin17] $ bundle install Fetching gem metadata from https://rubygems.org/.......... Fetching gem metadata from https://rubygems.org/. Resolving dependencies... Bundler could not find compatible versions for gem "activesupport":   In snapshot (Gemfile.lock):     activesupport (= 4.0.0)   In Gemfile:     sass-rails (~> 4.0.0) was resolved to 4.0.0, which depends on       sprockets-rails (~> 2.0.0) was resolved to

Rails 網站不顯示id的方法

Add Gem. (/Gemfile) 加 gem 到 Gemfile 中 gem 'friendly_id', '~> 5.1.0' gem 'babosa' 安裝套件 bundle install 建立Table ($rails c) rails g friendly_id rails g migration add_slug_to_posts slug:string:uniq rake db:migrate 修改Model (app/models/post.rb) class Post < ActiveRecord::Base   belongs_to :user, foreign_key: :user_id   has_many :comments   has_many :post_categories   has_many :categories, through: :post_categories   has_many :votes, as: :voteable   validates :title, presence: true, length: {minimum: 5}   extend FriendlyId   friendly_id :id, use: :slugged   # 原本是input.to_s.parameterize,但是parameterize只支援   # 英文跟數字,所以改用babosa的to_slug   def normalize_friendly_id(input)     input.to_s.to_slug.normalize.to_s   end   def should_generate_new_friendly_id?     slug.blank? || id_changed?   # slug 為 nil 或 name column 變更時更新   end   def slug_candidates     [ :id, [:id, :title]]   end end 使用friendly套件查找 (config/initializers/friendly_id.rb) config.us

has_secure_password

資料庫內雖然儲存密碼的欄位是“ password_digest ”,但是實際要把它的欄位名稱當成“ password ”來使用。 2.1.2 :001 > user = User.find_by username: "BBB"   User Load (0.6ms)  SELECT "users".* FROM "users" WHERE "users"."username" = 'BBB' LIMIT 1  => # 2.1.2 :002 > exit kuruwateki-MacBook-Air:postit-solution shawnkuo67$ rails c Loading development environment (Rails 4.0.0) 2.1.2 :001 > user = User.find_by username: "BBB"   User Load (0.7ms)  SELECT "users".* FROM "users" WHERE "users"."username" = 'BBB' LIMIT 1  => # 2.1.2 :002 > user. password = 'abcdef'  => "abcdef" 2.1.2 :003 > user.save    (0.2ms)  begin transaction Binary data inserted for `string` type on column ` password_digest `   SQL (6.0ms)  UPDATE "users" SET "password_digest" = ?, "updated_at" = ? WHERE "users"."id" = 2  [["

解決git push錯誤︰failed to push some refs to git

$ git push -u origin master To https://github.com/shawnkaku/postit.git ! [rejected] master -> master (non-fast-forward) error: failed to push some refs to 'https://github.com/shawnkaku/postit.git' hint: Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g. hint: 'git pull ...') before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details. $ git pull --rebase origin master From https://github.com/shawnkaku/postit  * branch            master     -> FETCH_HEAD First, rewinding head to replay your work on top of it... Applying: init $ git push origin master Counting objects: 65, done. Delta compression using up to 4 threads. Compressing objects: 100% (55/55), done. Writing objects: 100% (65/65), 15.23 KiB | 2.54 MiB/s, done. Total 65 (delta 2), reused 0 (delta 0) remote: Resolving deltas: 100% (2/2), done.

How to set Ruby on Rails Environment in mac (mac OS)?

1. install xcode in apple App Stor 2. curl -L https://get.rvm.io | bash -s stable 3. rvm -v 4. echo '[[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm" # Load RVM function' >> ~/.zshrc 5. rvm list known 6. rvm install 2.5.1 7. ruby -v 8. rvm rubygems current 9. gem -v 10. $ brew install git 11. $ git config --global user.name "YourName" 12. $ git config --global user.email "yourmail@gmail.com"  13. gem install bundler 14. gem install rails

Installing Passenger + Nginx

先查Ubuntu版本,指令會出現 Ubuntu 版本代碼。 lsb_release -a sudo apt-get install -y dirmngr gnupg sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 561F9B9CAC40B2F7 sudo apt-get install -y apt-transport-https ca-certificates sudo sh -c 'echo deb https://oss-binaries.phusionpassenger.com/apt/passenger xenial main > /etc/apt/sources.list.d/passenger.list' sudo apt-get update sudo apt-get install -y nginx-extras passenger 參考 Installing Passenger + Nginx  

How to set Ruby on Rails Environment in Linux (Ubuntu)?

Update your package manager first: $ sudo apt-get update This must finish without error or the following step will fail. Install  Curl : $ sudo apt-get install curl You’ll use Curl for installing  RVM . $ \curl -L https://get.rvm.io | bash vi ~/.bashrc # This loads RVM into a shell session. [[ - s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm" restart terminal. $ rvm get stable --autolibs=enable $ rvm install ruby $ rvm use 2.5.1 --default Nodejs $ sudo apt-get install nodejs $ gem install bundler $ gem install nokogiri $ gem install rails $ rails -v $ rails new AppName $ cd AppName $ rails s

How to install sublime-text-3 on ubuntu?

To get started, press Ctrl+Alt+T to open terminal, then follow below steps: 1.) Add sublime-text-3 in the repository. sudo add-apt-repository ppa:webupd8team/sublime-text-3 2.) Update the system with apt-get command. sudo apt-get update 3.) And install the latest Sublime Text 3 in your system. sudo apt-get install sublime-text-installer