使用has_many创建一个Ruby对象:through

时间:2018-07-04 03:03:12

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

假设我有以下模型:

implementation 'com.google.firebase:firebase-ml-vision:16.0.0'

如果我想当场创建课程和主题,我会这样做:

class Course < ActiveRecord::Base
  has_many :contents
  has_many :topics, :through => :contents
end

class Topic < ActiveRecord::Base
  has_many :contents
  has_many :courses, :through => :contents
end

class Content < ActiveRecord::Base
  belongs_to :courses
  belongs_to :topics
end

这将自动创建t1 = Topic.create(name: "Topic 1") t2 = Topic.create(name: "Topic 1") Course.create(name: "Course 1", topics: [t1, t2]) 记录。如果我在Content上添加了另一列,例如Content,是否可以快速创建课程,包括新的my_column列?

类似的东西:

Content

1 个答案:

答案 0 :(得分:3)

ActiveRecord::NestedAttributes是您要寻找的。

从文档中

  

嵌套属性允许您通过父级将属性保存在关联记录上。默认情况下,嵌套属性更新处于关闭状态,您可以使用#accepts_nested_attributes_for类方法启用它。启用嵌套属性时,将在模型上定义属性编写器。

我现在无法对其进行测试,但是您最终会做类似的事情,

class Course < ActiveRecord::Base
    has_many :contents
    has_many :topics, :through => :contents
    accepts_nested_attribute_for :topics
end

class Topic < ActiveRecord::Base
    has_many :contents
    has_many :courses, :through => :contents
end

class Content < ActiveRecord::Base
    belongs_to :courses
    belongs_to :topics
end


t1 = Topic.create(name: "Topic 1")
t2 = Topic.create(name: "Topic 1")
course = Course.new(name: "Course 1")
course.topics << t1
course.topics << t2

course.save!

puts course.topics # ... t1, t2

您还可以做更多的事情,包括在父级上即时创建新的子级记录。 docs和StackOverflow上面充斥着更多文档:)