如何创建rails关联

时间:2015-06-15 08:54:03

标签: ruby-on-rails rails-activerecord

如何创建这样的rails关联: enter image description here

和示例将显示如下: enter image description here

2 个答案:

答案 0 :(得分:0)

我假设您首先拥有users表,并且每个User对象has_onehas_many skill_setskill_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