如何创建这样的rails关联:
和示例将显示如下:
答案 0 :(得分:0)
我假设您首先拥有users
表,并且每个User
对象has_one
或has_many
skill_set
或skill_sets
分别
Table Name: users
id first_name last_name address
1 Arslan Ali ABC
2 Adnan Saqib ABC
3 Mahtab Maqsood ABC
对于表格,skill_sets
:
Table Name: skill_sets
id user_id dance_skill sing_skill model_skill
1 1 1 2 2
2 3 2 2 3
3 2 1 1 2
而且,在Rails中,你可以像下面这样建模:
class User < ActiveRecord::Base
has_one :skill_set # I'd go with one skill set per user
end
class SkillSet < ActiveRecord::Base
belongs_to :user # So it'd have 'user_id' in it.
end
对于迁移,我有类似的东西:
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.stirng first_name
t.string last_name
t.string address
t.timestamps null: false
end
end
end
class CreateSkillSets < ActiveRecord::Migration
def change
create_table :skill_sets do |t|
t.references :user, index: true
t.integer :dance_skill, null: false, default: 1
t.integer :sing_skill, null: false, default: 1
t.integer :model_skill, null: false, default: 1
end
end
end
我不明白,如果您所做的只是存储3行,为什么要使用表skills
。您可以在模型中使用以下内容:
class SkillSet < ActiveRecord::Base
SKILL_LEVEL = ["Good","Profi","Noob"]
def skill_level(number)
SKILL_LEVEL[number-1] # Arrays are based on zero-index.
end
# Now you can do user.skill_level(user.dance_skill)
# Other way: You can 'enums' as well, but it is up to you.
end
答案 1 :(得分:0)
您非常接近建立关联,您的问题非常简单。只需在模型skill_id
中添加字段TypeSkill
,而不是skill_model
。
并在模型中写一个简单的关联
在Skill
模块
has_many :type_skills # based on you requirement has_many or has_one
在TypeSkill
模型中
belongs_to :skill