Rails5.1.3でWebアプリケーション制作の勉強をしています。
customersテーブルと1体多で関連付けたhistoriesテーブルに新規にcustomersテーブルにレコードを保存すると同時にhistoriesテーブルにレコードを作りたいのですが上手く作れないので教えていただけないでしょうか?
$ rails c で試していますが上手くいかないので教えていただけないでしょうか?
customer.rb class Customer < ActiveRecord::Base has_many :histories, dependent: :destroy, autosave: true end
history.rb class History < ActiveRecord::Base belongs_to :customer end
customer_form.rb class Visitor::CustomerForm include ActiveModel::Model attr_accessor :customer, :inputs_home_address delegate :persisted?, :save, to: :customer def initialize(customer = nil) @customer = customer @customer ||= Customer.new (2 - @customer.personal_phones.size).times do @customer.personal_phones.build end self.inputs_home_address = @customer.home_address.present? @customer.build_home_address unless @customer.home_address @customer.build_histories unless @customer.histories ------ここが上手くいきません end
$ rails cで試した内容
irb(main):001:0> @customer = Customer.find(103) ---idが103のレコードを取得 irb(main):002:0> @customer.build_home_address unless @customer.home_address HomeAddress Load (0.4ms) SELECT `addresses`.* FROM `addresses` WHERE `addresses`.`type` IN ('HomeAddress') AND `addresses`.`customer_id` = 103 LIMIT 1 => #<HomeAddress id: nil, customer_id: 103, type: "HomeAddress", postal_code: nil, prefecture: nil, city: nil, address1: nil, address2: nil, created_at: nil, updated_at: nil>---home_addressのレコードは出来ているようです。 irb(main):003:0> @customer.build_histories unless @customer.histories => nil------nilとなり新規にレコードができていません。 試しにやってみたこと irb(main):017:0> @customer.histories History Load (0.4ms) SELECT `histories`.* FROM `histories` WHERE `histories`.`customer_id` = 103 LIMIT 11 => #<ActiveRecord::Associations::CollectionProxy []>
どなたか教えていただけないでしょうか?宜しくお願いします。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。