【问题标题】:how do i create new objects through activerecord associations如何通过 activerecord 关联创建新对象
【发布时间】:2019-07-17 11:15:20
【问题描述】:

我有一个表 Switches and Snapshots。一个 Switch 有很多 Snapshot,一个 Snapshot 属于一个 Switch。我无法通过关联创建新快照。在我的代码下方。

2.6.3 :014 > switch = Switch.new
 => #<Switch id: nil, switch: nil, ip_address: nil, created_at: nil, updated_at: nil> 
2.6.3 :015 > switch.create_snapshot
NoMethodError (undefined method `create_snapshot' for #<Switch:0x00000000039950e0>)

应用程序/模型

class Switch < ApplicationRecord

  has_many :snapshots

end

class Snapshot < ApplicationRecord

  belongs_to :switch

end

psql 通过迁移配置

\d switches
Indexes:
    "switches_pkey" PRIMARY KEY, btree (id)
Referenced by:
    TABLE "snapshots" CONSTRAINT "fk_rails_5537742698" FOREIGN KEY (switch_id) REFERENCES switches(id)

# \d snapshots
Indexes:
    "snapshots_pkey" PRIMARY KEY, btree (id)
    "index_snapshots_on_switch_id" btree (switch_id)
Foreign-key constraints:
    "fk_rails_5537742698" FOREIGN KEY (switch_id) REFERENCES switches(id)

【问题讨论】:

    标签: ruby-on-rails activerecord associations


    【解决方案1】:

    先创建switch,然后就可以像这样创建快照了

    switch = Switch.new 
    switch.save
    or
    switch = Switch.create(switch_params)
    

    然后

    switch.snapshots.create(snapshot_params)
    

    如果你想在创建开关的同时创建快照,那么你应该使用嵌套属性https://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

    【讨论】:

    • 确实有效。谢谢。在过去,我使用了提到的语法。这种变化或为什么我过去能够使用 switch.create_snapshot ?
    【解决方案2】:

    您需要在父模型上添加accepts_nested_attributes_for :model

    嵌套属性允许您通过父项保存关联记录的属性。默认情况下,嵌套属性更新是关闭的,您可以使用 #accepts_nested_attributes_for 类方法启用它。当您启用嵌套属性时,会在模型上定义一个属性编写器。 (来自api.rubyonrails.org

    【讨论】:

      【解决方案3】:

      要一起创建关联对象,可以有这样的替代方式-

      switch = Switch.new(swich_params)
      switch.snapshots.build
      switch.save
      

      创建switch 后,它还将创建关联的snapshots

      【讨论】:

        猜你喜欢
        • 2017-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-27
        相关资源
        最近更新 更多