【问题标题】:Rails 4.1 nested model form fieldsRails 4.1 嵌套模型表单字段
【发布时间】:2014-04-16 05:00:26
【问题描述】:

预订 -

class Booking < ActiveRecord::Base
  has_many :orders
end

class Order < ActiveRecord::Base
  belongs_to :booking
  has_many :transactions
end

class Transaction < ActiveRecord::Base
  belongs_to :order
end

我需要能够在不存在 OrderBooking 的情况下创建 Transaction

我正在努力实现以下目标: 当创建 Transaction 时,会自动创建 OrderBooking。交易表单可以取一个Booking.booking_number,它将被保存到上面自动创建的Booking

我对 Rails 很陌生,尝试了 accepts_nested_attributes_for、Ryan Bates 的 nested model form part1 screencastform_fields_for 的组合,但没有成功。

非常感谢一些指导,不一定是代码。

我的路线看起来像:

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    我需要能够在没有订单或预订的情况下创建交易 现有的。

    糟糕的系统设计 - 交易肯定会跟随订单或预订吗?

    根据您的问题,我强烈建议您先创建预订或订单。这将允许您创建一个事务作为对orderbooking 的补充:

    #app/controllers/bookings_controller.rb
    Class BookingsController < ApplicationController
       def create
           booking = Booking.new(booking_params)
           booking.save
       end
    end
    
    #app/models/booking.rb
    Class Booking < ActiveRecord::Base
        before_create :build_transaction #-> creates a blank transaction which can be populated later
    end
    

    尽管如此,没有什么能阻止您创建交易并稍后分配订单

    你可以这样做:

    #app/controllers/transactions_controller.rb
    def create
        Transaction.new(transaction_params)
    end
    
    #app/models/transaction.rb
    Class Transaction < ActiveRecord::Base
        after_create :order
    
        def order
            self.order.create!([order_details?])
        end
    end
    

    如果您告诉我更多关于您正在构建的内容,我将能够创建更精致的回复!

    【讨论】:

      【解决方案2】:

      试试这个可能会奏效。 在你的模型中 accepts_nested_attributes_for :order, :allow_destroy =&gt; true 根据您的表格更改真/假

      【讨论】:

      • 嗯,谢谢,但这与问题无关。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-11
      • 1970-01-01
      相关资源
      最近更新 更多