我很难想象如何在表中创建新条目并自动创建相关联的关系。
以下是我的模型:
class Building < ActiveRecord::Base
has_many :user_buildings
has_many :users, :through => :user_buildings
end
class User < ActiveRecord::Base
has_many :user_buildings
has_many :buildings, :through => :user_buildings
....
end
class UserBuilding < ActiveRecord::Base
belongs_to :user
belongs_to :building
end
现在我的用户模型也用于设备,所以我一直在使用current_user助手。
要检索所有建筑物,我使用:
current_user.buildings
所以我认为我可以使用这个方法:
current_user.buildings.build
创建一个与用户相关联的新建筑并更新连接表,但这只会将建筑添加到建筑表中,而不会在用户建筑表中进行关联。我一直在阅读http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html上的文档,但是我似乎无法确定我需要走的方向。谢谢!
user.buildings.create
可以正确地建立关系,而.build
和.save
则不行。 - Dogbertcurrent_user.buildings.build
时,应该按照以下方式保存:current_user.save
。 - apneadiving@building.new(params[:building])
,@building.save
,然后current_user.buildings << @building
来创建关联,使其正常工作。但是,使用create看起来更加优雅的解决方案。 - Nicholas DeLuca