我对RoR真的很陌生,所以如果我没有考虑清楚,我很抱歉。我有一个报告,我需要能够分配多个用户到该报告。一个用户可以分配给多个报表,一个报表可以有多个用户。如何创建允许这样做的数据库关系。我知道如何将一个用户分配给一个报表,但不知道如何将多个用户分配给单个报表。
我将使用一个连接类来实现这一点:
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
类Assignment
有两个字段:report_id
和user_id
来创建关系。
阅读Ruby on Rails Active Record Associations指南:http://guides.rubyonrails.org/association_basics.html
我强烈建议您熟悉Ruby on Rails指南。他们将被证明是无价之宝!!对于此任务,站点将是RailsGuides Active Record Associations。
在代码中,您需要创建三个数据库表:reports、reports_users和users,其中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
这将设置数据库和多对多模型连接。这将让你开始。现在我们要创建一些视图