rails在多对多关联中保存嵌套属性

时间:2018-06-11 13:39:49

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

我正在使用Rails 5。

这是我的数据库结构

create_table :apps do |t|
  t.text :tech_assist_info
  t.integer :scheduled
  t.integer :status
  t.text :notes
  t.belongs_to :operator, index: true, foreign_key: true
end

create_table :boards do |t|
  t.string :board_type
  t.string :registration_mark
  t.belongs_to :app, index: true, foreign_key: true
end

create_table :app_files do |t|
  t.string :name, null: false
  t.integer :file_type
  t.belongs_to :app, index: true, foreign_key: true
end

create_table :board_files do |t|
  t.belongs_to :app_file, index: true, foreign_key: true
  t.belongs_to :board, index: true, foreign_key: true
end

这是模型文件

# app.rb
class App < ApplicationRecord
  belongs_to :operator

  has_many :app_files
  has_many :boards

  accepts_nested_attributes_for :boards, :app_files, allow_destroy: true
end


#board.rb
class Board < ApplicationRecord
  belongs_to :app
  has_many :board_files
  has_many :app_files, through: :board_files

  accepts_nested_attributes_for :board_files, :app_files
end

#board_file.rb
class BoardFile < ApplicationRecord
  belongs_to :board
  belongs_to :app_file
end


#app_file.rb
class AppFile < ApplicationRecord
  belongs_to :app
  has_many :board_files
  has_many :boards, through: :board_files
end

提出以下问题

如何进行嵌套对象的保存/创建功能?

我正在尝试这个,但这不起作用。 我查看了文档http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

@app = App.new({
   tech_assist_info: "abc", status: 1, boards_attributes: [
           {board_type: "ABC55", registration_mark: "qwerty", app_files_attributes: [
           {name: "name.pdf", file_type: 5}]}
   ]
})

@app.save

由于

0 个答案:

没有答案
相关问题