Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 将新记录添加到新记录_Ruby On Rails_Validation_Activerecord_Append_Associations - Fatal编程技术网

Ruby on rails 将新记录添加到新记录

Ruby on rails 将新记录添加到新记录,ruby-on-rails,validation,activerecord,append,associations,Ruby On Rails,Validation,Activerecord,Append,Associations,我使用的是rails 4.1.6 我在创建新记录并保存它们时遇到问题。以下是模型: class Function < ActiveRecord::Base belongs_to :theater has_many :showtimes, dependent: :destroy belongs_to :parsed_show validates :theater, presence: :true validates :date, presence: :true end

我使用的是rails 4.1.6 我在创建新记录并保存它们时遇到问题。以下是模型:

class Function < ActiveRecord::Base
  belongs_to :theater
  has_many :showtimes, dependent: :destroy
  belongs_to :parsed_show

  validates :theater, presence: :true
  validates :date, presence: :true
end

class Theater < ActiveRecord::Base
  has_many :functions, :dependent => :destroy
  validates :name, :presence => :true
  accepts_nested_attributes_for :functions
end

class Showtime < ActiveRecord::Base
  belongs_to :function
  validates :time, presence: true
  validates :function, presence: true
end

showtime = Showtime.new time: Time.current
theater = Theater.first # read a Theater from the database
function = Function.new theater: theater, date: Date.current
function.showtimes << showtime
function.showtimes.count # => 0
类函数:destroy
验证:name,:presence=>:true
接受:函数的\u嵌套\u属性\u
终止
类Showtime

为什么showtime没有添加到函数的showtime中?我需要稍后将函数与showtimes一起保存。

您的
函数
对象尚未被持久化。在将内容添加到ShowTime列表之前,您需要确保它是持久的(当然,这也要求它是有效的)

尝试立即保存该函数,如果成功(即如果
函数.持久化?
),它应该允许您
您可以使用
函数#创建

theater = Theater.first # read a Theater from the database
function = Function.new theater: theater, date: Date.current
function.showtimes.create(time: Time.current)

我忘了检查保存函数是否也保存了影院,即使function.showtimes.count返回0,也会将放映时间保存到数据库中

function.showtimes.count返回:

=> 0
但是 function.showtimes返回:

=> #<ActiveRecord::Associations::CollectionProxy [#<Showtime id: nil, time: "2015-01-09 04:46:50", function_id: nil>]>
=>#