我有一个带有选择选项的订单模型(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
...来自models \ payment_type.rb
但我得到一个'空'?错误:
未定义的方法`空?对于#
我希望我的问题很明确,似乎有一个明显的解决方案,但到目前为止我还没有找到其他问题......
我将使用模型中的关系进行更新...
我的模特:
payment_type.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
order.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
答案 0 :(得分: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
您还需要更新订单模型中的验证声明:
validates :pay_type,
:presence => true,
:inclusion => { :in => proc { PaymentType.pluck(:pay_type_name) } }