相关疑难解决方法(0)

添加关联(<<)而不提交到数据库

在Rails中是否可以在不立即将此更改提交到数据库的情况下向现有记录添加关联?例如,如果我有Post has_many:标签

post.tags << Tag.first
Run Code Online (Sandbox Code Playgroud)

这将立即提交到数据库.我尝试过其他方式而不是<<,但没有成功(我想要的是在保存父对象时创建关联).是否有可能获得类似于使用build添加新记录的关联时的行为?

post.tags.build name: "whatever"
Run Code Online (Sandbox Code Playgroud)

我认为这在Rails中有点不一致,在某些情况下,选择执行此操作会很有用.

换句话说,我想要

post.tags << Tag.first # don't hit the DB here!
post.save # hit the DB here!
Run Code Online (Sandbox Code Playgroud)

ruby-on-rails ruby-on-rails-3

23
推荐指数
1
解决办法
5523
查看次数

具有has_many和has_one的多态关联的Factory Girl

我目前正在开发一个项目,我想用工厂女孩创建测试,但我无法使用多态has_many关联.我尝试了其他文章中提到的许多不同的可能性,但它仍然无效.我的模型看起来像这样:

class Restaurant < ActiveRecord::Base
  has_one :address, as: :addressable, dependent: :destroy
  has_many :contacts, as: :contactable, dependent: :destroy

  accepts_nested_attributes_for :contacts, allow_destroy: true
  accepts_nested_attributes_for :address, allow_destroy: true

  validates :name, presence: true
  #validates :address, presence: true
  #validates :contacts, presence: true
end

class Address < ActiveRecord::Base
  belongs_to :addressable, polymorphic: true

  # other unimportant validations, address is created valid, the problem is not here
end

class Contact < ActiveRecord::Base
  belongs_to :contactable, polymorphic: true
  # validations ommitted, contacts are created valid
end
Run Code Online (Sandbox Code Playgroud)

因此,我想要为餐厅创建一个地址和联系人的工厂(在餐厅进行验证,但如果不可能,即使没有它们),但我无法这样做.最终语法应该是:

let(:restaurant) { FactoryGirl.create(:restaurant) …
Run Code Online (Sandbox Code Playgroud)

rspec ruby-on-rails factory-bot

2
推荐指数
1
解决办法
3977
查看次数