在Rails 4中,如何同时创建Active Record对象和关联的has_many对象?

时间:2015-12-30 19:13:02

标签: ruby-on-rails activerecord

这里有两个模型:

class TeachingResource < ActiveRecord::Base
  has_many :links

  validates_presence_of :links
end

class Link < ActiveRecord::Base 
  belongs_to :teaching_resource

  validates_presence_of :teaching_resource
end

我们的想法是每个TeachingResource必须至少有一个Link

我正在尝试同时创建它们:

tr = TeachingResource.new({title: 'blah', description: 'blah'})
tr.links.build({href: 'whatever'})
tr.save!

# ActiveRecord::RecordInvalid: Validation failed: Resource objective links teaching resource can't be blank

如果我删除了validates_presence_of :teaching_resource,那么它会保存,但如果我在Rspec测试中执行此操作:expect(tr).to be_valid,则会发生这种情况:

# Links Each teaching resource must have at least one link

我为上述验证指定的自定义错误消息。

似乎教学资源ID没有被添加到新链接中,因为它已创建。这是设计的吗?创建这样两条记录的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

复制你的关联后,他们似乎运行良好:

describe Link, type: :model do
  let!(:teaching_resource) {FactoryGirl.build(:teaching_resource)}
  let!(:link){ teaching_resource.links.build}

  it "test" do
    expect(teaching_resource.persisted?).to be_falsey
    expect(teaching_resource.links.length).to eq(1)
    expect(teaching_resource).to be_valid
  end


class TeachingResource < ActiveRecord::Base
  has_many :links
  validates :links, presence: true
end

class Link < ActiveRecord::Base
  belongs_to :teaching_resource
  validates :teaching_resource, presence: true
end

尝试复制/粘贴此内容并查看测试是否通过

关联也在工厂中声明,但因为我使用的构建不会改变任何东西。

rails:4.2.5,ruby:2.2.2