【问题标题】:Rails: array created in one model, reach in from form in anotherRails:在一个模型中创建的数组,从另一个模型中的形式到达
【发布时间】:2012-11-16 16:53:47
【问题描述】:

我有一个带有选择选项的订单模型 (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?'错误:

未定义的方法`empty?'对于#

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

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

我的模型:

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

【问题讨论】:

  • 您确定您的方法没有返回 nil,并且数组的格式适合 select 方法吗?
  • 我很确定,因为我在一小时前在另一个错误中修复了该数组。该数组被传递到 order.rb 中用于验证语句,经过很长时间的弄清楚,它现在可以工作了。所以数组不能返回零。但我会检查控制台。是否可以在控制台中检查?抱歉,我对 RoR 很陌生,干杯

标签: ruby-on-rails arrays forms select models


【解决方案1】:

尝试使用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) } }

【讨论】:

  • 这会产生一个稍微不同的错误,我很害怕,因为我在过去两天里已经看到了 200 万次 :-( “您需要提供至少一个验证”
  • 它是否来自模型验证?您可以同时发布 PaymentType 验证和 Order 验证吗?
  • 可能与验证有关,但我不知道。它仍然说它来自浏览器中 _form.html.erb 中的第 28 行
  • 这行做什么/说什么?
  • 对不起,这一行是选择行,上面贴了数组
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多