Ruby on rails 将新记录添加到新记录
我使用的是rails 4.1.6 我在创建新记录并保存它们时遇到问题。以下是模型: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
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>]>
=>#