将新记录添加到新记录中

时间:2015-01-09 03:20:11

标签: 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

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

为什么showtime没有添加到该功能的放映时间?我需要稍后使用放映时间保存该功能。

3 个答案:

答案 0 :(得分:0)

您的Function对象尚未保留。在将内容添加到放映时间列表之前,您需要确保它是持久的(当然这也要求它有效)。

尝试保存函数beorehand,如果成功(即function.persisted?true),它应该允许您<<直接进入function.showtimes,就像你一样喜欢。或者,您可以使用Function#create类方法而不是Function#new类方法,因为前者会自动保留记录。

答案 1 :(得分:0)

您可以使用Function#create

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

答案 2 :(得分:0)

我忘了检查保存功能是否也保存了剧院,即使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>]>
相关问题