Created
June 27, 2011 04:47
-
-
Save ayasuda/1048322 to your computer and use it in GitHub Desktop.
has many 関連を拡張したいが、命名ややり方に迷いが生じてしまいました。同じ by_master で動作が違うのはちょっとどうかと思いますが、どうすればいいでしょうか?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 仮に RPG 的なソーシャルゲームだとして。。。 | |
# | |
# == 前提 | |
# | |
# * 武器やボスは、ユーザーとの中間テーブルとマスターデータが別テーブルになってます。 | |
# * User <>--- Weapon ---<> WeaponMaster 的な。 | |
# * User は同じ種類の (master の id が同じ) 武器をいっぱい持てます。 | |
# * User は同じ種類のボスはひとつしか持てないです。 | |
# | |
# == やりたい事 | |
# | |
# 同じ種類のボスはひとつしか持てないので。。。 | |
# | |
# user = User.find 1 | |
# user.bosses.by_master(1) #=> 中間テーブルがあるなら Boss を返してほしい | |
# user.bosses.by_master(100) #=> 中間テーブルが無いなら RecordNotFound を投げてほしい | |
# | |
# == 気持ち悪いこと | |
# | |
# 同じ種類の武器は複数しか持てるので。。。 | |
# | |
# user = User.find 1 | |
# user.weapons.by_master(1) #=> こっちは Array を返してほしい。 | |
# user.weapons.by_master(100) #=> 無いなら [] になってほしい。 | |
# | |
# == そもそも。。。 | |
# | |
# 何故、Association extensions と named scope を同時に使ってしまったのか。。。 | |
# | |
class User < ActiveRecord::Base | |
has_many :weapons | |
has_many :bosses do | |
def by_master(master_id) | |
where("master_id = ?", master_id) | |
end | |
end | |
end | |
# composite key ジャナイ | |
class Weapon < ActiveRecord::Base | |
belogs_to :user | |
scope :by_master, lambda{|master_id| where("master_id = ?", master_id} | |
end | |
# composite key ハイッテル | |
class Boss < ActiveRecord::Base | |
set_primary_keys :user_id, :master_boss_id | |
belogs_to :user | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment