您在rails迁移中使用Uniq的哪一方面

时间:2018-03-05 14:42:31

标签: ruby-on-rails orm relationship has-and-belongs-to-many

在我的rails应用中,我有2个模型public class BaseController : Controller { public ActionResult Index() { //print AController - Index } // Add more methods to be shared between the other controllers } public class AController : BaseController { // Has Index method already from parent // Unique method for A public ActionResult Test() { //print test 1 } } public class BController : BaseController { // Has Index method already from parent // Unique method for B public ActionResult Test() { //print test 2 } } Profile

Skill has_and_belongs_to_many Profile并且只能有一次Skill

Skill has_and_belongs_to_many Skill。如果我们尊重第一个关系,那么它应该不会超过一次Profile

当我创建连接表时,我有两种可能性:

Profile

rails g migration CreateProfilesSkillsJoinTable profiles:uniq skills

第一个选项将生成

rails g migration CreateProfilesSkillsJoinTable profiles skills:uniq

第二个将生成

class CreateProfilesSkillsJoinTable < ActiveRecord::Migration[5.1]
  def change
    create_join_table :profiles, :skills do |t|
      t.index [:profile_id, :skill_id], unique: true
      # t.index [:skill_id, :profile_id]
    end
  end
end

1 个答案:

答案 0 :(得分:1)

您希望使索引唯一:

add_index :something, [:profile_id, :skill_id], unique: true

首先验证了第一条规则(您只能获得1:2一次)。请注意,即使有了habtm,您也倾向于以相同的方式创建关系(profile.skills << skill),您只需要确保skill.profiles << profile不会产生不需要的关系