[rails]関連(1対1)
所有しているテーブル側のモデルにhas_one
所属している側のモデルにbelongs_toを設定する。
例:studentsテーブルが、profilesテーブルを所有(profilesテーブルは、studentsテーブルに所属)している場合。
studentsテーブルのカラム
id,name
profilesテーブルのカラム
id,student_id,name
赤字の部分(所有する側のテーブル名の単数形+"_id")をカラムとして定義する。
そして、studentsのモデルは以下のように記述
class Student < ActiveRecord::Base
has_one :profile
end
profiles側はこう
class Profile < ActiveRecord::Base
belogns_to :student
end
これで、profiles側のコントローラ等で"student"の名前でstudentsテーブルを参照できるし、
students側からは"profile"の名前でprofilesテーブルを参照できるようになる。
« ruby/LDAPでADに接続する | トップページ | 3/3 自転車のライト »
「ruby/rails」カテゴリの記事
- acts_as_paranoid(2008.04.01)
- ActiveScaffoldで表示するレコードを設定する(2008.03.31)
- ActiveCalendarの入力フォーマットを変える(2008.03.24)
- ActiveScaffoldListFilters(2008.03.21)
- Activescaffoldでdate/datetimeをカレンダーで入力する(2008.03.21)
コメント