0

私はRubyを始めたばかりです。私は Sinatra で小さなアプリを作成しており、sqlite3 db で Datamapper を使用しています。

以下は、私が作成している 3 つのモデルです。

class Team
  include DataMapper::Resource
  property :id, Serial
  property :name, String, :required => true
  property :created_at, DateTime
  property :updated_at, DateTime
end

class Poll
  include DataMapper::Resource
  property :id, Serial
  property :name, String, :required => true
  property :created_at, DateTime
  property :updated_at, DateTime
end

class Ranking
  include DataMapper::Resource
  property :year, Integer
  property :week, Integer
  property :ranking, Integer
  property :votes, Integer
  property :created_at, DateTime
  property :updated_at, DateTime

  belongs_to :team, :key => true
  belongs_to :poll, :key => true
end

私ができるようにしたいのは、特定の投票、週、年についてランキング モデルをクエリすることです。

返される結果は、各ランキング番号に関連付けられたチームのその投票のすべてのランキングである必要があります。

したがって、たとえば 2011 年 - 第 1 週または 2011 年 - 第 7 週などのランキングと、各ランキングに対応するチームを取得します。

私は一日中これを機能させる方法を見つけようとしてきましたが、どこにも行きません。そのため、ここに投稿して助けを求めています.

4

1 に答える 1

0

まず、Datamapper gem について聞いたことがないと言っておきましょう。Rails のモデルと移行について考え続けるのがより簡単になるので、気にしないでください。

データモデルについていくつかコメントがあります:

  • モデルを誤解していない限り、すべての日付関連のフィールドはランキング テーブルではなく投票テーブルに入れる必要があると思います。ランキング テーブルのフィールドは、チームと投票の関係を説明する必要があります。
  • 投票日に単一のフィールドを使用してcommercialから、コントローラでメソッドのようなものを使用して、特定の週内に投票を取得する必要があります。(出典: http://apidock.com/ruby/Date/commercial/class )
  • 必要に応じて、総投票数など、投票に関連する追加データを保存することもできます。それらは投票テーブルにも入ります。

モデル

アプリ/モデル/team.rb

class Team < ActiveRecord::Base
    has_many :rankings
    has_many :polls, through: :rankings
    validates :name, :presence => true
end

アプリ/モデル/poll.rb

class Poll < ActiveRecord::Base
    has_many :rankings
    has_many :teams, through: :rankings
    validates :name, :presence => true
end

アプリ/モデル/ranking.rb

class Ranking < ActiveRecord::Base
    belongs_to :team
    belongs_to :poll
end

移行

デシベル/移行/create_teams.rb

class CreateTeams < ActiveRecord::Migration
    def change
        create_table :teams do |t|
            t.string :name
            t.timestamps
        end
    end
end

デシベル/移行/create_polls.rb

class CreatePolls < ActiveRecord::Migration
    def change
        create_table :polls do |t|
            t.string :name
            t.date :published_at
            t.timestamps
        end
    end
end

デシベル/移行/create_rankings.rb

class CreateRankings < ActiveRecord::Migration
    def change
        create_table :rankings do |t|
            t.integer :team_id
            t.integer :poll_id
            t.integer :votes
            t.integer :ranking
            t.timestamps
        end
    end
end

関係を確認するためのテスト アプリケーションをセットアップする時間がなかったので、うまく機能したかどうか教えてください。

于 2012-08-12T04:06:40.433 に答える