【问题标题】:Why isnt the join table for has_many through created in rails when using new/save versus create?为什么在使用 new/save 与 create 时没有通过在 rails 中创建的 has_many 连接表?
【发布时间】:2021-04-08 01:22:07
【问题描述】:

这是在轨道 4.2.11.3 上。我有一个 has_many through 关系设置如下:

class ProgramCourse < ActiveRecord::Base
  belongs_to :course
  belongs_to :program
end

class Course < ActiveRecord::Base
  has_many :program_courses
  has_many :programs, -> { uniq }, through: :program_courses
end

class Program < ActiveRecord::Base
  has_many :program_courses
  has_many :courses, -> { uniq }, through: :program_courses
end

如果我创建这样的课程:

c = program.courses.create(name: 'Amazing Course')

ProgramCourse 记录与新的Course 一起创建。但是,如果我这样做:

c = program.courses.new(name: 'Amazing Course')
c.save

仅创建 Course。这是一个错误吗?我的关系在语法上有什么问题吗?谁能解释一下为什么这两者不同?

【问题讨论】:

  • 在第二个示例中使用“build”而不是“new”是否有效?前一段时间它们曾经是不同的方法,我不确定 ROR4
  • 这能回答你的问题吗? using has_many :through and build

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


【解决方案1】:
class ProgramCourse < ActiveRecord::Base
  belongs_to :course
  belongs_to :program
end

class Course < ActiveRecord::Base
  has_many :program_courses
  has_many :programs, -> { uniq }, through: :program_courses
end

class Program < ActiveRecord::Base
  has_many :program_courses
  has_many :courses, -> { uniq }, through: :program_courses
  accepts_nested_attributes_for :program_courses, :courses
end

你需要在模型中添加这个才能使用这个或者你可以使用build方法来创建关联记录

c = program.courses.build(name: 'Amazing Course')
c.save

【讨论】:

    猜你喜欢
    • 2016-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-18
    • 1970-01-01
    • 2015-03-23
    • 1970-01-01
    • 2011-05-28
    相关资源
    最近更新 更多