0

我有一个带有选择选项的订单模型(orders_form.html.erb)的表单视图:

<%= f.select :pay_type, PaymentType.array_of_payment_types,
             :prompt => 'Select a payment method' %>

PaymentType 是另一个模型, .array_of_payment_types 是根据 payment_type_name 列中的条目创建的数组,如下所示:

def self.array_of_payment_types
  @array_of_payment_types ||= PaymentType.pluck(:pay_type_name)
end

...来自模型\payment_type.rb

但我得到一个 proc 'empty?' 错误:

未定义的方法“空?” 为了 #

我希望我的问题很清楚,似乎有一个明显的解决方案,但到目前为止我还没有找到一个阅读其他问题的人......

我将更新模型中的关系......

我的模型:

付款类型.rb:

class PaymentType < ActiveRecord::Base
  attr_accessible :pay_type_name

  has_many :orders

  validates :pay_type_name, :uniqueness

  def self.names
    all.collect { |pt| pt.pay_type_name }
  end 

  def self.array_of_payment_types
    PaymentType.all.map{ |p| [p.pay_type_name, p.id] }
  end
end

订单.rb:

class Order < ActiveRecord::Base
  attr_accessible :address, :email, :name, :pay_type, :payment_type_id, :cart_id, 
                  :product_id

  has_many :line_items, :dependent => :destroy
  belongs_to :payment_type

  #PAYMENT_TYPES = ['Check','Purchase order','Credit card']

  validates :name, :address, :email, :presence => true
  validates  :pay_type,
             :presence => true,
             :inclusion => { :in => proc { PaymentType.array_of_payment_types } }

  def add_line_items_from_cart(cart)
    cart.line_items.each do |item|
      item.cart_id = nil
      line_items << item
    end
  end
end
4

1 回答 1

0

尝试使用options_for_select

# in the view:
<%= f.select :pay_type, options_for_select(PaymentType.array_of_payment_types),
         :prompt => 'Select a payment method' %>

# in the PaymentType model:
def self.array_of_payment_types
  PaymentType.all.map{ |p| [p.pay_type_name, p.id] }
end

您还需要更新 Order 模型中的 validates 语句:

validates  :pay_type,
           :presence => true,
           :inclusion => { :in => proc { PaymentType.pluck(:pay_type_name) } }
于 2012-11-16T17:03:37.860 回答