【发布时间】:2011-07-01 16:36:57
【问题描述】:
我无法弄清楚如何在表中创建新条目并在连接表中自动创建关联关系。
这是我的模型:
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
创建与用户关联的新建筑物并更新连接表;但是,这只会将建筑物添加到建筑物表中,而不会在 user_buildings 表中建立关联。
我一直在阅读http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html 的文档,但我似乎无法弄清楚我需要走的方向。
谢谢!
【问题讨论】:
-
在我看来像一个 Rails 错误。
user.buildings.create确实建立了正确的关系,而.build和.save没有。 -
当你做
current_user.buildings.build时,你应该保存如下:current_user.save -
@apneadiving:这仅在您在关联上设置 :autosave 选项时有效(请参阅@nicholas 指出的文档)
-
谢谢大家!在我阅读这些 cmets 之前,我最终通过做
@building.new(params[:building])、@building.save,然后current_user.buildings << @building在连接中建立关联来让它工作。然而,使用 create 看起来是一个更优雅的解决方案。 -
如果您找到答案,请关闭问题。
标签: mysql ruby-on-rails ruby ruby-on-rails-3