简答
添加到图像和视频模式:
accepts_nested_attributes_for :content
的证明
我很肯定我知道这个问题的答案,但不知道它是否与多态联系起作用离子(我以前没有用过),所以我设置了一个小测试。
创建模型的方式与您的设置相同,但具有名称属性以及可用于验证失败的验证。
class Image < ActiveRecord::Base
has_one :content,
as: :contentable,
inverse_of: :contentable,
dependent: :destroy
validates_length_of :name, maximum: 10
end
class Content < ActiveRecord::Base
belongs_to :contentable,
inverse_of: :content,
polymorphic: true
validates_length_of :name, maximum: 10
end
下设置的迁移,像这样:
class CreateImages < ActiveRecord::Migration
def change
create_table :images do |t|
t.string :name
t.timestamps null: false
end
end
end
class CreateContents < ActiveRecord::Migration
def change
create_table :contents do |t|
t.string :name
t.references :contentable, polymorphic: true, index: true
t.timestamps null: false
end
end
end
下一页写一个RSpec测试父不会被保存,如果孩子不能保存和验证错误perculate起来。
it 'should not save image if content is invalid' do
image = Image.new()
image.name = 'this is ok'
expect(image).to be_valid
content = Content.new()
content.name = 'a string that should fail validation'
image.content = content
expect(image).to_not be_valid
image.save
expect(image).to_not be_persisted
expect(content).to_not be_persisted
expect(image.errors.count).to eq(1)
expect(image.content.errors[:name][0]).to include('is too long')
end
冉测试,果然失败。
下一页添加以下行到图像(视频)
accepts_nested_attributes_for :content
测试现在通 - 即,如果孩子未通过验证的父母也将无法通过验证,将无法保存。
您正在使用哪种版本的导轨? – dnsh
@Dinesh Rails 4.2.6 – geoboy
为什么你要像这样设置它 - 除非你提出最终目标,否则“推荐方法”是不可行的 - 分离这样的项目的原因究竟是什么 - 模型/模式看起来像你的应用程序需要这种分离? – MageeWorld