代码之家  ›  专栏  ›  技术社区  ›  Derk153

栏杆。通过嵌套属性实现多对多集合关系

  •  1
  • Derk153  · 技术社区  · 8 年前

    我一直在想如何设置 has_many, through: 使用嵌套属性的关系。

    我有以下型号:

    用户.rb

    class User < ApplicationRecord
       has_many :user_tags
       has_many :tags, through: :user_tags
    
       accepts_nested_attributes_for :user_tags,
                                allow_destroy: true,
                                reject_if: :all_blank
    end
    

    用户标签.rb

    class UserTag < ApplicationRecord
      belongs_to :tag
      belongs_to :user
    
      accepts_nested_attributes_for :tag
    
      validates :tag, :user, presence: true
      validates :tag, :uniqueness => {:scope => :user}
      validates :user, :uniqueness => {:scope => :tag}
    end
    

    标签.rb

    class Tag < ApplicationRecord
      has_many :user_tags
      has_many :users, through: :user_tags
    
      validates :title, presence: true, uniqueness: true
    end
    

    相关的 模式

      create_table "user_tags", id: :integer, force: :cascade do |t|
        t.integer  "user_id"
        t.integer  "tag_id"
        t.index ["tag_id"], name: "index_user_tags_on_tag_id", using: :btree
        t.index ["user_id"], name: "index_user_tags_on_user_id", using: :btree
      end
    
      create_table "tags", id: :integer, force: :cascade do |t|
        t.string   "title"
        t.string   "language"
        t.integer  "type"
        t.datetime "created_at", null: false
        t.datetime "updated_at", null: false
      end
    

    所有标记都是预定义的,无法修改。 我只需要建立和破坏 tags users 在模型中 user_tag ,在用户通过嵌套属性创建/更新操作中。

    类似于:

    params = { user: {
          user_tags_attributes: [
              { id: 1, _destroy: '1' }, # this will destroy association
              { tag_id: 1 }, # this will create new association with tag, which id=1 if tag present
              { tag_title: 'name' } # this will create new association with tag, which title='name' if tag present
          ]
      }}
    
    user.update_attributes(params[:user])
    

    确切的问题是,我无法创建ONYL关联,但我可以通过关联创建或更新标记。

    我正在使用 栏杆5.0

    1 回复  |  直到 8 年前
        1
  •  0
  •   Derk153    8 年前

    我找到了解决问题的办法。我有错误 UserTag 验证。

    我变了

      validates :tag, :uniqueness => {:scope => :user}
      validates :user, :uniqueness => {:scope => :tag}
    

      validates :tag_id, :uniqueness => {:scope => :user_id}
      validates :user_id, :uniqueness => {:scope => :tag_id}
    

    标签分配正在工作。

    Reman寻找如何通过以下方式破坏关联的解决方案 tag_id ,没有关联id