資料表關聯設定
ActiveRecord可以用Associtions來定義資料表之間的關聯性。
一對多關係 one-to-many
代表一個events有多個attendees
rails g model events name:string
# 建立attendee表的model
rails g model attendee name:string event_id:integer
class Event < ActiveRecord::Base
validates_presence_of :name
has_many :attendees # 複數
end
class Attendee < ActiveRecord::Base
belongs_to :event
end
#routes.rb
resources :events do
resources :attendees, :controller => "attendees"
end
本作品採用《CC 協議》,轉載必須註明作者和本文連結