1

레일을 사용하고 있습니다. 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 

왜 쇼 타임이 기능의 상영 시간에 추가되지 않습니까? 나중에 상영 시간표를 사용하여이 기능을 저장해야합니다.

답변

0

Function 개체가 보존되지 않았습니다. 상영 시간 목록에 항목을 추가하기 전에 해당 항목이 유지되는지 확인해야합니다 (물론 유효해야 함).

는 함수 beorehand을 저장 시도하고 성공 (function.persisted?true 경우 즉) 경우 당신이 원하는대로, 그것은 직접 function.showtimes<< 당신을 허용해야합니다. 또는, Function#new 클래스 메서드 대신 Function#create 클래스 메서드를 사용할 수 있습니다. 전자 메서드는 자동으로 해당 레코드를 유지하기 때문입니다.

0

당신은 내가 기능을 절약 또한 극장을 저장, 심지어 function.showtimes.count 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) 
0

를 사용할 수 있습니다.

function.showtimes.count 반환 :

=> 0 

하지만 function.showtimes 반환 :

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