【问题标题】:Add new record to a new record将新记录添加到新记录
【发布时间】:2015-01-09 03:20:10
【问题描述】:

我正在使用 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

为什么没有将放映时间添加到函数的放映时间?我需要稍后保存该函数以及它的放映时间。

【问题讨论】:

    标签: ruby-on-rails validation activerecord append associations


    【解决方案1】:

    您的Function 对象尚未持久化。您需要确保它是持久的(当然这也要求它是有效的),然后才能将内容添加到其放映时间列表中。

    尝试保存函数beorehand,如果成功(即function.persisted?true),它应该允许您将&lt;&lt;直接存入function.showtimes,随心所欲。或者,您可以使用Function#create 类方法代替Function#new 类方法,因为前者会自动保留记录。

    【讨论】:

      【解决方案2】:

      您可以使用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)
      

      【讨论】:

        【解决方案3】:

        我忘记检查保存函数是否也保存了剧院,即使 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>]>
        

        【讨论】:

          猜你喜欢
          • 2022-01-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-02-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-01-18
          相关资源
          最近更新 更多