熱門文章

顯示具有 rails 標籤的文章。 顯示所有文章
顯示具有 rails 標籤的文章。 顯示所有文章

2017年2月20日 星期一

常見的 Ruby on Rails 工程師面試問題

常見的 Ruby on Rails 工程師面試問題

收錄一些業界常見/常問的面試問題和翻譯解答

解答不見得完整和精確,但在面試的環境下回答應該是足夠的

有需要改正或有什麼要新增 / 補充的地方也請大家發 PR

開始閱讀

2016年11月16日 星期三

[Rails]Rails 5 开发进阶 -GitBooks



Rails 5 开发进阶

本书主要包括两部分:Rails 源码剖析和 Rails 使用指南。Rails 是一个 Web 开发框架,也是一个工具。"工欲善其事必先利其器",想要更好的使用 Rails 这个工具,清楚其背后的魔法,阅读源代码是必备功课。
本书尽量做到系统、全面,从源码出发,会讲解到原理。本书大部分内容为原创,少数内容为整理网上资料,鉴于参考资料太多,恕我不能一一列举来源。

本书适合什么样的读者?

  • 想要更好的使用 Rails
  • 准备阅读 Rails 的源代码
  • 想知道 Rails 的整体架构
  • 想清楚 Rails 背后的魔法

本书包含了哪些内容?

  • 一些文档里找不到的方法
  • 每个模块的关键所在
  • 源码阅读路线图

本书不讲哪些内容?

  • 安装、部署
  • 奇技淫巧
  • Ruby 语法、Rails 入门
  • 和具体业务相关的问题或功能
  • 非常具体、底层的代码实现

本书目的

  • 让使用其它语言、框架的技术人员,能看懂是什么
  • 让已经入门的 Rails 使用人员,知道更多原理,能看懂怎么用

联系我

邮箱:leekelby@gmail.com

2016年10月31日 星期一

[Rails]資料庫可以使用哪些資料型態?如何存array,json ?

Here are all the Rails 4 (ActiveRecord migration) datatypes:
  • :binary
  • :boolean
  • :date
  • :datetime
  • :decimal
  • :float
  • :integer
  • :bigint
  • :primary_key
  • :references
  • :string
  • :text
  • :time
  • :timestamp
If you use PostgreSQL, you can also take advantage of these:
  • :hstore
  • :json
  • :array
  • :cidr_address
  • :ip_address
  • :mac_address
They are stored as strings if you run your app with a not-PostgreSQL database.
Edit, 2016-Sep-19:
There's a lot more postgres specific datatypes in Rails 4 and even more in Rails 5.

[rails]do each 用法 (with index)

在ruby裡面,大家都用do each 的方法來完成其他程式的for 迴圈

基本的用法  each do


irb(main):013:0> a=[1,2,3,4,5,6]
=> [1, 2, 3, 4, 5, 6]
irb(main):022:0> a.each do |b|
irb(main):023:1* puts b    
irb(main):024:1> end
1
2
3
4
5
6
=> [1, 2, 3, 4, 5, 6]



這樣可以達到for loop的功效 且很簡短 不用再寫 當...大於...時..i++ 這麼長了
但,有一個問題,那當我要有 i++ 這樣遞增或遞減的序號時怎麼做?

答案很簡單  each_with_index do

irb(main):030:0> b=[12,22,23,44,66,22]
=> [12, 22, 23, 44, 66, 22]
irb(main):031:0> b.each_with_index do |b,index|
irb(main):032:1* puts "我是第#{index+1} 筆資料,為'#{b}' 謝謝"
irb(main):033:1> end
我是第1 筆資料,為'12' 謝謝
我是第2 筆資料,為'22' 謝謝
我是第3 筆資料,為'23' 謝謝
我是第4 筆資料,為'44' 謝謝
我是第5 筆資料,為'66' 謝謝
我是第6 筆資料,為'22' 謝謝
=> [12, 22, 23, 44, 66, 22]


參考:http://ruby-doc.org/core-1.8.7/Enumerable.html#method-i-each_with_index


2016年10月17日 星期一

[Rails]AJAX筆記-使用內建方式

使用內建ajax的方法

  1. 在from_for 加入 remote:true
  2. 在controller的相對應action,加入format.js (create action)
  3. 新增相對應action的js擋( create.js.erb)











when there is a file field in a form is submitted via AJAX.
在使用Ajax時,如果form裡面有file_field遇到問題

ActionController::InvalidAuthenticityToken error. 



ActionController::InvalidAuthenticityToken in StoresController#create

Avoiding ActionController::InvalidAuthenticityToken on AJAX calls



Missing Authenticity Token in Remote Forms w/ File Upload Field(s) #22807




解決方法一:在form_for 加入  :authenticity_token => true
可以成功執行Create Action,但是不會以Ajax的方式執行

<%= form_for @some_model, :remote => true, :authenticity_token => true do |f| %>
<% end %>


解決方法二:

當form_for 改為 :remote=>true時 ,form 將不會包含 authenticity_token
因為以下預設值為false
config.action_view.embed_authenticity_token_in_remote_forms = false 


將其改為true即可修正錯誤

config.action_view.embed_authenticity_token_in_remote_forms = true
官方解釋
  • config.action_view.embed_authenticity_token_in_remote_forms allows you to set the default behavior for authenticity_token in forms with remote: true. By default it's set to false, which means that remote forms will not include authenticity_token, which is helpful when you're fragment-caching the form. Remote forms get the authenticity from the meta tag, so embedding is unnecessary unless you support browsers without JavaScript. In such case you can either pass authenticity_token: true as a form option or set this config setting to true.

2016年10月8日 星期六

[Rails]ActiveRecord::Migration - 改變欄位資料型態

Step 1:
Generate a new migration file using this code:
rails g migration sample_name_change_column_type
Step 2: 
Go to /db/migrate folder and edit the migration file you made. There are two different solutions.
  1. def change
        change_column(:table_name, :column_name, :new_type)
    end
2.
    def up
        change_column :table_name, :column_name, :new_type
    end

    def down
        change_column :table_name, :column_name, :old_type




    end
Step 3:
Don't forget to do this command:
rake db:migrate


實際操作:
在command 下,新增migration 檔案
➜  eat git:(master) ✗ rails g migration sample_name_change_column_type
Running via Spring preloader in process 74424
      invoke  active_record

      create    db/migrate/20161008204016_sample_name_change_column_type.rb

在sublime text 開啟

自行修改欄位,依序是資料表名稱、欄位名稱、新的資料型態。

在此示範的是將 reviews資料表裡的rating欄位改成float 資料型態。
 change_column(:table_name, :column_name, :new_type)



在command 下

➜  eat git:(master) ✗ rake db:migrate
== 20161008204016 SampleNameChangeColumnType: migrating =======================
-- change_column(:reviews, :rating, :float)
   -> 0.0064s

== 20161008204016 SampleNameChangeColumnType: migrated (0.0065s) ==============


在rails c 下測試
可以看到紅色處由integer改為float

irb(main):002:0> a = Review.last
  Review Load (0.2ms)  SELECT  "reviews".* FROM "reviews" ORDER BY "reviews"."id" DESC LIMIT ?  [["LIMIT", 1]]
=> #<Review id: 14, rating: 3, comment: "3.5", created_at: "2016-10-08 08:15:48", updated_at: "2016-10-08 08:15:48", user_id: 3, store_id: nil>
irb(main):003:0> a.rating.class
=> Fixnum
irb(main):004:0> a.rating.class
=> Fixnum
irb(main):005:0> exit
➜  eat git:(master) ✗ rails c
Running via Spring preloader in process 74494
Loading development environment (Rails 5.0.0.1)
airb(main):001:0> a= Review.last
  Review Load (0.2ms)  SELECT  "reviews".* FROM "reviews" ORDER BY "reviews"."id" DESC LIMIT ?  [["LIMIT", 1]]
=> #<Review id: 14, rating: 3.0, comment: "3.5", created_at: "2016-10-08 08:15:48", updated_at: "2016-10-08 08:15:48", user_id: 3, store_id: nil>

irb(main):002:0> 





2016年9月23日 星期五

[Rails]simple_form 錯誤 error -undefined method 'number?'


undefined method 'number?' for #<ActiveRecord::ConnectionAdapters::PostgreSQLColumn:0x007fd89fda3d40>





解決方法>> 更改你的Gemfile


gem 'simple_form'

to

gem 'simple_form', github: 'kesha-antonov/simple_form', branch: 'rails-5-0'




然後bundle install,重開server  Done

2016年9月22日 星期四

[文字編輯器]Sublime Text好用套件-Emmet




手動安裝可參考 :https://www.minwt.com/webdesign-dev/html/11624.html




這邊使用的是sublime2


安裝步驟

1.下載Sublime Text https://www.sublimetext.com/3


2.安裝Package Control

2-1開啟sublime 並開啟Console (位置在最上方的view > Show Console


 可以看到下方出現console
2-2 輸入相對版本的指令 https://sublime.wbond.net/installation

Sublime Text 2

import urllib2,os,hashlib; h = '261dd1222b4693ce6d4f85f9c827ac06' + '6d5ab8ebdd020086947172a8a1356bb6'; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); os.makedirs( ipp ) if not os.path.exists(ipp) else None; urllib2.install_opener( urllib2.build_opener( urllib2.ProxyHandler()) ); by = urllib2.urlopen( 'http://packagecontrol.io/' + pf.replace(' ', '%20')).read(); dh = hashlib.sha256(by).hexdigest(); open( os.path.join( ipp, pf), 'wb' ).write(by) if dh == h else None; print('Error validating download (got %s instead of %s), please try manual install' % (dh, h) if dh != h else 'Please restart Sublime Text to finish installation')
2-3 重開


3.安裝Emmet

3-1 開啟package controller  (Sublime Text2 > perferences >Package Control) 
或快捷鍵(command+shift+p)


3-2 選擇 Package Control:Install Package



3-3 Package Control 視窗會消失,請再開啟一次 (command+shift+p),並輸入emmet
選擇第一個( 並非我途中所顯示的那個,因為我已經安裝所以不會顯示)


這個才是正確的Emmet (youtube 截圖 from :https://www.youtube.com/watch?v=8n923UBjV9w)

3-4重開 !!完成




再來是操作 ,在sublime 開啟 html檔案,以下是簡易的教學影片

輸入 .[class name] 後,按鍵盤的Tab鍵 即可變成
<div class="[class name]"></div>
幫你省下許多時間






更多外掛介紹及教學

http://www.slideshare.net/banPrint/sublime-text-51689543

2016年8月15日 星期一

[rails]form-tag

>>index.html.erb

<%= form_tag(groups_path, method: "get") do %>
  <%= label_tag(:q) %>
  <%= text_field_tag(:q) %>
  <%= submit_tag("搜索") %>
<% end %>
<%= @a %>
</div>


groups_path  :處理的路徑
:q 將被存在 controller 裡相對路徑的 method 裡
此範例是 groupscontroller.rb的 index 裡如下

def index
@groups = Group.all
a = params[:q]
end

對網頁應用程式來說,表單是非常重要的用戶輸入介面。Rails在這方面也提供了很多好用的Helper方法。基本上,Rails處理表單分成兩種類型:
一種是對應到Model物件的新增、修改,我們會使用form_for這個Helper。它的好處在於透過傳入Model物件,可以在修改的時候自動幫你將預設值帶入。例如我們已經在Part1使用過的event表單:
<%= form_for @event do |f| %>
    <%= f.text_field :name %>
    <%= f.submit %>
<% end %>
另一種是就是沒有對應Model的表單,我們使用form_tag這個方法。例如:
<%= form_tag "/search" do %>
    <%= text_field_tag :keyword %>
    <%= submit_tag %>
<% end %>
和form_for有些類似,但是其中不需要傳Block變數f,其中的欄位Helper需要多加_tag結尾。不像form_for的欄位名稱一定要是Model的屬性之一,在form_tag之中的欄位名稱則完全不受限。


form_tag 是啥?跟 form_for 有什麼不一樣?

Adler @ 2015-07-18

2016年8月9日 星期二

2016年7月28日 星期四

[RoR]Address already in use - bind(2) (Errno::EADDRINUSE)

Address already in use - bind(2) (Errno::EADDRINUSE)

當出現錯誤 already in use:


bundle exec puma -C config/puma.rb
[23699] Puma starting in cluster mode...
[23699] * Version 2.11.3 (ruby 2.0.0-p353), codename: Intrepid Squirrel
[23699] * Min threads: 5, max threads: 5
[23699] * Environment: development
[23699] * Process workers: 2
[23699] * Preloading application
Jdbc-MySQL is only for use with JRuby
[23699] * Listening on tcp://0.0.0.0:3000
/.rvm/gems/ruby-2.0.0-p353/gems/puma-2.11.3/lib/puma/binder.rb:210:in `initialize': Address already in use - bind(2) (Errno::EADDRINUSE)
    from /.rvm/gems/ruby-2.0.0-p353/gems/puma-2.11.3/lib/puma/binder.rb:210:in `new'
    from /Users/lexi87/.rvm/gems/ruby-2.0.0-p353/gems/puma-2.11.3/lib/puma/binder.rb:210:in `add_tcp_listener'
    from /.rvm/gems/ruby-2.0.0-p353/gems/puma-2.11.3/lib/puma/binder.rb:96:in `block in parse'
    from /.rvm/gems/ruby-2.0.0-p353/gems/puma-2.11.3/lib/puma/binder.rb:82:in `each'
    from /.rvm/gems/ruby-2.0.0-p353/gems/puma-2.11.3/lib/puma/binder.rb:82:in `parse'
    from /.rvm/gems/ruby-2.0.0-p353/gems/puma-2.11.3/lib/puma/runner.rb:119:in `load_and_bind'
    from /.rvm/gems/ruby-2.0.0-p353/gems/puma-2.11.3/lib/puma/cluster.rb:302:in `run'
    from /.rvm/gems/ruby-2.0.0-p353/gems/puma-2.11.3/lib/puma/cli.rb:216:in `run'
    from /rvm/gems/ruby-2.0.0-p353/gems/puma-2.11.3/bin/puma:10:in `<top (required)>'
    from /.rvm/gems/ruby-2.0.0-p353/bin/puma:23:in `load'
    from /.rvm/gems/ruby-2.0.0-p353/bin/puma:23:in `<main>'
    from /.rvm/gems/ruby-2.0.0-p353/bin/ruby_executable_hooks:15:in `eval'
    from /.rvm/gems/ruby-2.0.0-p353/bin/ruby_executable_hooks:15:in `<main>'


解決方法:

To kill the puma process first run 
    lsof -wni tcp:3000 
to show what is using port 3000. Then use the PID that comes with the result to run the kill process. 
For example after running lsof -wni tcp:3000 you might get something like 
    COMMAND  PID  USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
    ruby    3366 dummy    8u  IPv4  16901      0t0  TCP 127.0.0.1:3000 (LISTEN)
Now run kill -9 3366
Should resolve the issue