我正在构建一个简单的 Rails 应用程序(这是我的第一个 Rails 项目),用于跟踪组内用户的统计信息。我已经使用迁移脚本创建了表,当我在 MySql 中查看时,一切看起来都正常,但当我将它们连接到另一个表时,并非所有模型都返回数据。
有人发现我的模型、迁移脚本或数据模型有什么问题吗?
这是我的迁移文件脚本代码:
class CreateGroupsUsers < ActiveRecord::Migration
def change
create_table :types do |t|
t.string :name
end
create_table :groups do |t|
t.string :name
t.belongs_to :type, index: true
end
create_table :users do |t|
t.string :username
t.string :email
t.string :first_name
t.string :last_name
t.string :e_password
t.string :salt
t.timestamps
end
create_table :roles do |t|
t.string :name
end
create_table :groups_users, id: false do |t|
t.belongs_to :group, index: true
t.belongs_to :user, index: true
t.belongs_to :role, index: true
end
create_table :statistics do |t|
t.string :name
end
create_table :groups_users_statistics, id: false do |t|
t.string :value
t.belongs_to :group, index: true
t.belongs_to :user, index: true
t.belongs_to :statistic, index: true
end
end
end
这是我的模型:
class Type < ActiveRecord::Base
has_many :groups
end
class Role < ActiveRecord::Base
has_many :groups_users
end
class User < ActiveRecord::Base
has_and_belongs_to_many :groups
has_one :roles, through: :groups_users
end
class Group < ActiveRecord::Base
has_and_belongs_to_many :users
has_one :types
end
class Statistic < ActiveRecord::Base
//i'm not too sure how to define this model
end
这是我的数据模型
最佳答案
我根据 Esse、Pavan 和 AndyV 的评论更新了我的模型。现在一切似乎都运行良好
class Type < ActiveRecord::Base
has_many :groups
end
class Role < ActiveRecord::Base
has_many :group_users
end
class User < ActiveRecord::Base
has_many :group_users
has_many :groups, through: :group_users
has_many :group_user_statistics
has_many :groups, through: :group_user_statistics
has_many :statistics, through: :group_user_statistics
end
class Group < ActiveRecord::Base
has_many :group_users
has_many :users, through: :group_users
has_many :group_user_statistics
has_many :users, through: :group_user_statistics
has_many :statistics, through: :group_user_statistics
end
class GroupUser < ActiveRecord::Base
belongs_to :group
belongs_to :user
end
class Statistic < ActiveRecord::Base
has_many :group_user_statistics
has_many :groups, through: :group_user_statistics
has_many :users, through: :group_user_statistics
end
class GroupUserStatistic < ActiveRecord::Base
belongs_to :user
belongs_to :group
belongs_to :statistic
end
关于mysql - ActiveRecord 关联 : am I doing it right?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36453442/