Rails:多对多的关系 - 创建和关联新记录

时间:2017-10-11 22:06:01

标签: ruby-on-rails ruby-on-rails-4 many-to-many has-many-through

我正在查看此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>

1 个答案:

答案 0 :(得分:0)

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

2步骤:   - 创建CourseLocation   - 关联CourseLocationCourse

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

如果您想在一步中执行此操作,可以使用Active Record accepts_nested_attributes_for method,这有点棘手。这是一个good article,但让我们打破这些步骤:

  1. 课程需要接受course_localizations的属性
  2. 课程本地化需要接受course_location的属性
  3. 创建课程时,请传递包含位置属性的本地化属性。
  4. 让我们为你的特定情况设置所有这些:

    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