![](/img/trans.png)
[英]How to create associated object on the has_many relationship using rails?
[英]In Rails 4, how can I create an Active Record object and an associated has_many object at the same time?
這是兩個模型:
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並未在創建時添加到新鏈接中。 這是設計使然嗎? 創建這樣兩個記錄的正確方法是什么?
復制您的關聯后,它們似乎運行良好:
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
嘗試復制/粘貼此內容,看看測試是否通過
關聯也在工廠中聲明,但是由於我使用的是build,因此不會更改任何內容。
導軌:4.2.5,紅寶石:2.2.2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.