Tag: 后保存

Rails 4在保存时创建关联对象

在保存新主对象后,如何自动创建多个关联对象? 例如 在Rails 4中,我有三个对象: 企业 , 预算和类别 。 #app/models/business.rb class Business < ActiveRecord::Base #attrs id, name has_many :budgets end #app/models/budget.rb class Budget < ActiveRecord::Base #attrs id, business_id, department_id, value belongs_to :business belongs_to :category end #app/models/category.rb class Category < ActiveRecord::Base #attrs id, name has_many :budgets end 当我创建新业务时,在保存新业务之后,我想为每个类别自动创建预算并给它$ 0的值。 这样,当我去展示或编辑新的业务时,它将已经具有相关的类别和预算,然后可以对其进行编辑。 因此,在创建新业务时,将创建多个新预算,每个类别对应一个,每个都具有值0。 我读了这篇文章: Rails 3,如何在创建主记录后添加关联记录(Books,Auto Add BookCharacter) 我想知道我是否应该在Business模型中使用after_create回调,然后在Budgets控制器中存在逻辑(不完全确定如何执行此操作),或者我是否应该在’new’中添加logic_controller.rb的逻辑用类似的东西打电话: […]

rspec测试has_many:through和after_save

我有一个(我认为)相对简单的has_many :through与连接表的关系: class User :user_following_thing_relationships end class Thing :user_following_thing_relationships, :source => :user end class UserFollowingThingRelationship < ActiveRecord::Base belongs_to :thing belongs_to :user end 这些rspec测试(我知道这些不一定是好的测试,这些只是为了说明发生了什么): describe Thing do before(:each) do @user = User.create!(:name => “Fred”) @thing = Thing.create!(:name => “Foo”) @user.things << @thing end it "should have created a relationship" do UserFollowingThingRelationship.first.user.should == @user UserFollowingThingRelationship.first.thing.should == @thing […]