【问题标题】:Rails. Many to many set relation via nested attributes导轨。通过嵌套属性设置多对多关系
【发布时间】:2016-05-31 08:27:03
【问题描述】:

我一直试图弄清楚如何使用嵌套属性设置has_many, through: 关系。

我有以下型号:

user.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

user_tag.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

tag.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

所有标签都是预定义的,不能修改。 我只需要在模型user_tag 中通过嵌套属性在用户的创建/更新操作中设置和销毁tagsusers 之间的关系。

类似:

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 关联,但我可以通过关联创建或更新标签。

我正在使用 Rails 5.0

【问题讨论】:

  • 您遇到的具体问题是什么?您能否也发布 schema.rb 的相关部分。
  • @JanBussieck:我已将 schema.rb 添加到我的问题中。问题是我无法创建 ONYL 关联。当我执行user.update_attributes(user_tags_attributes: [{tag_id: 1}]) 时,预计将为用户创建 ID=1 的标签关联,但出现错误。 user.errors.messages =&gt; {:"user_tags.tag.title"=&gt;["has already been taken"]} 我假设它正在尝试创建新标签。 UserTag 表为空且用户没有关联的标签
  • 你去吧:你得到一个错误,因为你试图创建一个标题已经被占用的标签,所以你的验证 validates :title, presence: true, uniqueness: true 阻止创建记录。

标签: ruby-on-rails ruby nested-attributes ruby-on-rails-5


【解决方案1】:

我找到了解决问题的方法。我在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}

并且标签分配正在工作。

重新找到解决方案如何通过tag_id 破坏关联,没有关联ID

【讨论】:

    猜你喜欢
    • 2014-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多