我正在查看此railscast #17 revised作为使用连接表在两个模型之间创建多对多关系的教程:
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
如果用户在编辑或创建courselocation
时未看到现有course
,那么他们创建新courselocation
并自动建立关联的最佳方式是什么?< / p>
答案 0 :(得分:0)
您可以通过两步流程(我的首选方法)或一步完成此操作。
2步骤:
- 创建CourseLocation
- 关联CourseLocation
和Course
。
course_location1 = CourseLocation.create(name: 'location1')
course.course_locations << course_location1
如果您想在一步中执行此操作,可以使用Active Record accepts_nested_attributes_for
method,这有点棘手。这是一个good article,但让我们打破这些步骤:
让我们为你的特定情况设置所有这些:
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