1

私はスカベンジャー ハント アプリに取り組んでいますが、それを正しくモデリングしているかどうかを知りたいだけです。ユーザーが参加できるハントのリストがあります。これらのハントは、カスタマイズ可能なテンプレートです (特定のタスクの追加/削除など)。

ユーザーが狩りに行くことを選択したとき、私はそれを「旅行」と呼んでいます。アソシエイトに関する Rails ガイドを読みましたが、トリップ モデルをユーザーとハント間の結合テーブルとして設定する必要があると考えています。これが私が考えていることです。

    class Users 
      has_many :trips
      has_many :hunts, :through => :trips

    class Hunts
      has_one :trip
      has_many :users, :through => : trips

    class Trip
      belongs_to :users
      belongs_to :hunts

次に、Trip テーブルをセットアップする移行は次のようになります。

    def change
      trip_name
      user_id
      hunt_id
    end

2 つの質問があります。

  1. これは正しく見えますか?
  2. これを行うためのよりスマートな(またはよりエレガントな)方法はありますか?

更新:これが私がやったことです。

    class Users 
      has_many :trips
      has_many :hunts, :through => trips

    class Hunts
      has_one :trip
      has_many :users, :through => trips

    class Trip
      belongs_to :hunts
      belongs_to :users

その後

    def change
      create_table :trips do |t|
        t.string :trip_name
        t.references :user
        t.references :hunt
      end
      add_index :trips, :hunt_id
      add_index :trips, :user_id
      add_index :trips, [:hunt_id, :user_id], :unique => true
    end
4

3 に答える 3

1

あなたは関連付けを複雑にしています。Hunts : Trip = 1 : 1 であるため、両方をユーザーに関連付ける必要はありません。

class Users 
  has_many :hunts
  has_many :trips, :through => hunts

class Hunts
  has_one :trip
  has_many :users

class Trip
  belongs_to :hunt  # belongs to singular word. :)

次に、次のようなテーブル「users_hunts」を作成します。

# users_hunts table, has 3 columns:
id
user_id
hunt_id 

trips テーブルは次のようになります。

# trip table , has 1 extra column: 
id 
hunt_id
于 2012-05-20T21:34:52.993 に答える
1

私は一緒に行きます

class Users 
  has_many :trips
  has_many :hunts, :through => trips

class Hunts
  has_one :trip
  has_many :users, :through => trips

class Trip
  belongs_to :hunts
  belongs_to :users

両方の方法で関係をまだ必要としていない場合でも、理解しやすく (imho)、将来に向けて設定されているため、ユーザーが多くのユーザーを獲得したり、多くのユーザーを獲得したりできます。これは非常に実現可能と思われます。

于 2012-05-20T21:40:27.170 に答える
1

小さな問題がいくつか見られます。

  1. モデルは慣用的に単数形です: 変化UsersHunts、異常な状況がない限り。
  2. Huntおそらく、has_many :tripsそうですか?
  3. あなたの移行は疑わしいほどまばらです。メソッドは通常、次のchangeようになります。

.

def change
  create_table :trips do |t|
    t.string :trip_name
    t.references :user
    t.references :hunt
  end
end

構造的に、あなたが持っているものは私にとって理にかなっています。

余談ですが、私はスカベンジャー ハントと呼ばれることもある冒険を組織しました。

于 2012-05-20T21:29:26.223 に答える