轨道:多对多关系 - 创建和关联新记录



我正在查看这个 railscast #17 修订为教程,以使用连接表在两个模型之间创建多对多关系:

class Course < ActiveRecord::Base
has_many :courselocalizations
has_many :courselocations, through: :courselocalizations
end
class Courselocation < ActiveRecord::Base
has_many :courselocalizations
has_many :courses, through: :courselocalizations
end
class Courselocalization < ActiveRecord::Base
belongs_to :course
belongs_to :courselocation
end

如果用户在编辑或创建course时看不到现有courselocation,那么创建新courselocation并自动进行关联的最佳方式是什么?

您可以通过 2 步过程(我的首选方法)或一步完成此操作。

2步流程: - 创建CourseLocation - 关联CourseLocationCourse

course_location1 = CourseLocation.create(name: 'location1')
course.course_locations << course_location1


如果您想分一步完成此操作,可以使用活动记录accepts_nested_attributes_for方法,这有点棘手。 这是一篇关于它的好文章,但让我们分解步骤:

  1. 课程需要接受属性course_localizations
  2. 课程本地化需要接受属性course_location
  3. 创建课程时,传递本地化的属性,其中包含位置的属性。

让我们为您的特定情况设置所有这些:

class Course < ActiveRecord::Base
  # attribute subject
  has_many :course_localizations, inverse_of: :course
  has_many :course_locations, through: :course_localizations
  accepts_nested_attributes_for :course_localizations
end
class CourseLocation < ActiveRecord::Base
  # attribute city
  has_many :course_localizations
  has_many :courses, through: :course_localizations
end
class CourseLocalization < ActiveRecord::Base
  belongs_to :course
  belongs_to :course_location
  accepts_nested_attributes_for :course_locations
end

此时,您应该能够

course = Course.new(
  subject: "Math",
  course_localizations_attributes: [
    { course_location_attributes: { city: "Los Angeles" } },
    { course_location_attributes: { city: "San Francisco" } }]
)
course.save

最新更新