【问题标题】:Cannot create many-to-many relationship无法创建多对多关系
【发布时间】:2018-02-01 13:19:11
【问题描述】:

我不会在 ruby​​ on rails 中创建多对多关系。当我尝试保存新的词汇表时,我总是遇到错误。

“词汇表类别无效”

这是我的代码:

def create(glossary_params)
  Glossary.transaction do
       @glossary = Glossary.new(name: glossary_params[:name],
                   identifier: glossary_params[:identifier],
                   description: glossary_params[:description],
                   private_glossary: glossary_params[:private_glossary])

      glossary_params[:categories_id].each do |c|
         @glossary.glossary_categories.build(category: Category.find_by_id(c), user: @user)
     end
  end
  @glossary
end

这是我的词汇表模型:

class Glossary < ApplicationRecord
  validates :name, presence: :true, uniqueness: { case_sensitive: false }
  validates :identifier, presence: :true, uniqueness: { case_sensitive: false }

  has_many :glossary_categories
  has_many :categories, through: :glossary_categories
end

这是我的类别模型:

class Category < ApplicationRecord
   has_many :glossary_categories
   has_many :glossaries, through: :glossary_categories
end

这是我的 GlossaryCategory 模型:

class GlossaryCategory < ApplicationRecord
   belongs_to :glossary
   belongs_to :category
   belongs_to :user
end

这是我的词汇表类别表:

create_table :glossary_categories do |t|
  t.belongs_to :glossary, index: true
  t.belongs_to :category, index: true
  t.integer :user_id
  t.timestamps
end

【问题讨论】:

  • glossary_categories 有哪些列?问题很可能就在那里......如果你可以编辑你的问题以包含这个,我想你会很快得到答案:)
  • 我编辑了我的问题,您现在可以看到我的表创建命令。
  • 嗯 - 看起来不错(可能也需要在 user_id 上的索引)。你在使用 Rails 5 吗?如果是这样,您能否将optional: true 添加到您的联接表的belongs_to 关系中再试一次?我想知道@userCategory.find_by_id(c) 是否为零并导致此问题。让我知道这是怎么回事,如果有帮助,我会回答!
  • 我使用 Rails 5。我尝试将 'optional:ture' 添加到我的连接表中。之后词汇表被保存在数据库中,但没有 GlossaryCategory。然后我尝试'@glossary.glossary_categories.create',但我得到了异常You cannot call create unless the parent is saved。如何在事务中正确执行此操作?

标签: ruby-on-rails ruby-on-rails-5 rails-activerecord


【解决方案1】:

我的创建方法的解决方案是:

def create(glossary_params)
   Glossary.transaction do
      @glossary = Glossary.create(name: glossary_params[:name],
                   identifier: glossary_params[:identifier],
                   description: glossary_params[:description],
                   private_glossary: glossary_params[:private_glossary])

      if @glossary.valid?
         if glossary_params[:categories_id].present?
            glossary_params[:categories_id].each do |c|
                @glossary.glossary_categories.create(category: Category.find_by_id(c), user: @user)
            end
         end
      end
   end
   @glossary
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    相关资源
    最近更新 更多