0

私はRoRを初めて使用するので、これについて正しく考えていない場合は申し訳ありません。複数のユーザーをそのレポートに割り当てる必要があるレポートがあります。ユーザーは複数のレポートに割り当てることができ、レポートには複数のユーザーを含めることができます。これが許可されるデータベース関係を作成するにはどうすればよいですか。1 人のユーザーを 1 つのレポートに割り当てる方法は理解していますが、1 つのレポートに多くのユーザーを割り当てる方法は理解していません。

4

2 に答える 2

2

これを実現するには、結合クラスを使用します。

class Report

  has_many :assignments 
  has_many :users :through => :assignments

end

class User

  has_many :assignments
  has_many :reports, :through => :assignments

end

class Assignment

  belongs_to :report
  belongs_to :user

end

このクラスには、リレーションシップを作成するとのAssignment2 つのフィールドがあります。report_iduser_id

アクティブ レコード アソシエーションに関する Ruby on Rails ガイドをお読みください: http://guides.rubyonrails.org/association_basics.html

于 2013-03-03T05:33:53.633 に答える
0

Ruby on Rails ガイドに慣れることを強くお勧めします。かけがえのない財産となるでしょう!! このタスクでは、サイトはRailsGuides Active Record Associationsになります。

コードが進む限り、reports、reports_users、および users の 3 つのデータベース テーブルを作成する必要があります。reports_users は結合テーブルです。

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string      :name,        :null => false      
      t.timestamps
    end
  end
end


class CreateReports < ActiveRecord::Migration
  def change
    create_table :reports do |t|
      t.string      :name,        :null => false      
      t.timestamps
    end
  end
end


class ReportsUsers < ActiveRecord::Migration
  def change
    create_table :reports_users, :id => false do |t|
      t.references    :user,            :null => false                            
      t.references    :report,          :null => false                            
    end
  end
end

この移行を実行したら、モデルでアクティブなレコードの関連付けを設定する必要があります。

class User < ActiveRecord::Base
  has_and_belongs_to_many :reports
end

class Report < ActiveRecord::Base
  has_and_belongs_to_many :user
end

これにより、データベースと多対多モデル接続が設定されます。これで始められます。次に、いくつかのビューを作成する必要があります

于 2013-03-03T05:43:12.837 に答える