2009年12月1日火曜日

rails、 :includeの使い方について

Ruby on Railsについて。(個人情報はxxxx)

Active Recordの:include の機能を利用して2つのテーブルを結合しようとしたところ、エラー。


G先生: :include はN 対1 の1 側からしか発行できないよ。

じぶん: ぇ・・・

G先生: とりあえずSQL を直接発行した方がいいかな。

じぶん: mjsk


いろいろ調べたがSQL を使おうとした際に,困ったことが

テーブル'grade' (多) とテーブル'syllabus' (1) で,
@grades = Grade.find_by_sql("SELECT grade.* syllabus.* from grade, syllabus where grade.class_ID = syllabus.class_ID and grade.gakuseki_number = 'xxxx';")
とすると、Gradeクラスからの発行となり、おかしい。

初心に帰り、:include の勉強をすることに。

↓↓↓
・結果
:include 使える。

原因は各テーブルのモデルにあったらしい。

-誤
※grades.rb
class Grade < ActiveRecord::Base
belongs_to :syllabuses
belongs_to :students
end

-正
class Grade < ActiveRecord::Base
belongs_to :syllabus, :foreign_key => 'syllabus_id'
belongs_to :student,:foreign_key => 'student_id'
end
#belongs_to (対1) なのでテーブル+(e)sはおかしい
#foreign_key として'対象のテーブル名_id' を指定する

とする。

また,:includeの利用方法は
@grades = Grade.find(:all,:conditions => ['gakuseki_number = ?','xxxx'],:include => :syllabus)
とする.
※ポイントは:include => :syllabus

テーブルsyllabusのメソッドを呼び出すときは
@grades.syllabus.○○
とすればよい。


参考URL
http://code.nanigac.com/source/wiki/view/641/50
以上。

0 件のコメント:

コメントを投稿