【发布时间】:2016-04-06 14:00:19
【问题描述】:
我正在构建一个简单的 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
这是我的数据模型
【问题讨论】:
-
我认为你应该尽量避免使用
has_and_belongs_to_many,而使用has_many through -
您在
type模型中有has_many :groups,而在group模型中有has_one :types,这是错误的,无法正常工作。 -
@Pavan 你会推荐使用什么来代替?
-
你应该把
has_one :types改成belongs_to :type。 -
@Esse 如果我通过 has_many 使用,是否需要为交叉表定义模型?
标签: mysql ruby-on-rails ruby activerecord