有的變數變前面有一個冒號(例如 :name),是什麼意思?
隨便打開一個 Rails 專案,應該都看過類似像這樣的內容:
class User < ActiveRecord::Base
has_many :products
validates :name, presence: true
end
class Product < ActiveRecord::Base
belongs_to :user
end
或是
class ProductController < ApplicationControl
before_action :find_product
# .. 中略
private
def find_product
@product = Product.find_by(id: params[:id])
end
end
這在 Rails 專案裡是很常見的寫法,但這裡 :products
、:user
、:name
以及 :find_product
是什麼意思呢? 用一般的字串或變數不行嗎?