代码之家  ›  专栏  ›  技术社区  ›  Kamal G'ool

第二个嵌套模型的多个t.reference值为零

  •  0
  • Kamal G'ool  · 技术社区  · 10 年前

    我通过两个t.references访问了belongs_to owner和belongs_to car,当我通过@car.visits.create创建新访问时,owner_id始终为零。

    访问.rb

    class Visit < ActiveRecord::Base
    #validates :notes, presence:true
    belongs_to :car
    belongs_to :owner
    end
    

    所有者.rb

    class Owner < ActiveRecord::Base
    has_many :cars
    has_many :visits    
    accepts_nested_attributes_for :visits
    accepts_nested_attributes_for :cars
    end
    

    汽车.rb

    class Car < ActiveRecord::Base
    belongs_to :owner
    has_many :visits
    end
    

    访问迁移

    class CreateVisits < ActiveRecord::Migration
    def change
    create_table :visits do |t|
      t.boolean :open
      t.text :notes
      t.references :owner
      t.references :car
      t.timestamps null: false
    end
    
    end
    end
    

    如果我

     car1 = Car.create(......)
     car1.visits.create(.....)
    

    我得到了访问的价值。owner_id=nil,但是,car_id完全填充了正确的关系。

    我错过了什么? 非常感谢您的帮助。

    example from my console where owner_id: nil even when its created from a @car who has already owner_id

    1 回复  |  直到 10 年前
        1
  •  0
  •   taglia    10 年前

    如果我的理解是正确的,你的问题是,在你的关系中,你在Car中强制执行owner_id和在Visit中强制执行的owner_id应该是相同的。你的模型将支持一辆属于某个车主的汽车,但却与属于其他人的拜访相连;因此,当您创建访问时,rails会将ownerid保留为零,因为它不知道该属于哪个所有者。

    三种简单的解决方案:

    1. 您可以完全删除Owner和Visit之间的关系,只需创建您需要的方法,这将从Car调用相应的方法:

      class Visit < ActiveRecord::Base
        belongs_to :car
      
        def owner_id
          car.owner_id
        end
      
        def owner
          car.owner
        end
      end
      
    2. 在create语句中明确指定所有者: car1.visits.create(owner: car1.owner, .....)

    3. 在回调中将owner_id设置为正确的值:

      class Visit < ActiveRecord::Base
        belongs_to :car
        belongs_to :owner
      
        before_create do
          self.owner_id = car.owner_id
        end
      end