我如何解决方法缺失错误,在轨控制台
问题描述:
已经样板碟和PriceDeal如下我如何解决方法缺失错误,在轨控制台
class Dish < ActiveRecord::Base
has_one :price_deal
end
class Dish < ActiveRecord::Base
belongs_to :dish
end
在轨控制台,我想以检索这样的discountPercent值。
1.9.2p290 :130 > pd=PriceDeal.find(17)
=> #<PriceDeal id: 17, name: "deal1", description: "my deal1", discountPercent: 20.0, discountCash: nil, dish_id: 2, created_at: "2012-03-22 07:42:08", updated_at: "2012-04-16 11:16:49">
1.9.2p290 :131 > pd.discountPercent
=> 20.0
我得到了预期的结果。
但是,当我试图让这样的价值,
1.9.2p290 :132 > pd1 = PriceDeal.where(:dish_id => 2)
=> [#<PriceDeal id: 17, name: "deal1", description: "my deal1", discountPercent: 20.0, discountCash: nil, dish_id: 2, created_at: "2012-03-22 07:42:08", updated_at: "2012-04-16 11:16:49">]
1.9.2p290 :133 > pd1.discountPercent
NoMethodError: undefined method `discountPercent' for #<ActiveRecord::Relation:0xa134958>
from /home/ragunathjawahar/.rvm/gems/[email protected]/gems/activerecord-3.0.11/lib/active_record/relation.rb:374:in `method_missing'
from (irb):133
from /home/ragunathjawahar/.rvm/gems/[email protected]/gems/railties-3.0.11/lib/rails/commands/console.rb:44:in `start'
from /home/ragunathjawahar/.rvm/gems/[email protected]/gems/railties-3.0.11/lib/rails/commands/console.rb:8:in `start'
from /home/ragunathjawahar/.rvm/gems/[email protected]/gems/railties-3.0.11/lib/rails/commands.rb:23:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
我有错误,
如何获得discountPercent从PD1的价值。
谢谢。
答
为什么发生这种情况的原因是因为当你使用where
,你回来不PriceDeal
类型的单个对象,但你得到ActiveRecord::Relation
类型的对象,这对于所有意图和目的是数组。
通知你如何:
[#<PriceDeal id: 17, name: "deal1", ... >]
而不只是:
#<PriceDeal id: 17, name: "deal1", ... >
大括号([]
)意味着它是一个数组。所以你必须要做到这一点:
pd1.first.discountPercent
为什么where
方法返回一个数组的原因是因为你可以有多个项目返回。想象一下:
PriceDeal.where("discountPercent >= 0")
你可能会从中得到很多记录。
答
PD = PriceDeal.find(17)
它只会返回一个特定column.so你不会得到任何方法的错误。
当你使用Modelname.where(“条件”)。结果将是array.so,你将不会有方法error.Because你的方法不存在数组。
我们也会接受“类似数组的对象” – 2012-04-16 14:29:37
是的,这可能是更好的放置方式,因为关系首先查找数组方法,然后查找类方法。 – MrDanA 2012-04-16 14:39:50