无法创建多对多关系

时间:2018-02-01 13:19:12

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

我无法在rails上的ruby中创建多对多的关系。当我尝试保存新词汇表时,我总是收到错误。

“词汇表类别无效”

这是我的代码:

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

这是我的glossary_category表:

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

1 个答案:

答案 0 :(得分:0)

我的create方法的解决方案是:

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