【问题标题】:Rails 3 Automatically Making Joined Table AssociationsRails 3 自动建立连接表关联
【发布时间】: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 &lt;&lt; @building 在连接中建立关联来让它工作。然而,使用 create 看起来是一个更优雅的解决方案。
  • 如果您找到答案,请关闭问题。

标签: mysql ruby-on-rails ruby ruby-on-rails-3


【解决方案1】:

您需要更新当前用户的建筑物集合,rails 将为您处理更新连接表。

current_user.buildings << Building.new(:some_building_attributes => :some_value)
current_user.save

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多