Rails关联 - 如何获取最大值?

时间:2018-06-01 13:57:48

标签: ruby-on-rails rails-activerecord

我有两个相关的模型如下:

出价模式:

belongs_to :car_ad

CarAd型号:

has_many :bids

def max_bidvalue
  bids.max(:bid_value)
end

虽然我可以获取特定于汽车的所有出价,但当我尝试获取最高bid_value时,我会收到如下错误:

mycar = CarAd.find(149)

mycar.bids
+----+------------+-----------+---------+-----------+--------------+-------------+------------+-------------+-------------+---------------+
| id | auction_id | car_ad_id | user_id | bid_value | increment... | ip_address  | user_agent | bid_time    | created_at  | updated_at    |
+----+------------+-----------+---------+-----------+--------------+-------------+------------+-------------+-------------+---------------+
| 1  | 1          | 149       | 35      | 1100      | 100          | 10.10.10.10 | test       | 2018-06-... | 2018-06-... | 2018-06-01... |
| 2  | 1          | 149       | 36      | 1500      | 400          | 10.10.10.10 | test       | 2018-06-... | 2018-06-... | 2018-06-01... |
| 3  | 1          | 149       | 35      | 1600      | 100          | 10.10.10.10 | test       | 2018-06-... | 2018-06-... | 2018-06-01... |
+----+------------+-----------+---------+-----------+--------------+-------------+------------+-------------+-------------+---------------+
3 rows in set

 mycar.bids.max(:bid_value)
      Bid Load (0.5ms)  SELECT "bids".* FROM "bids" WHERE "bids"."car_ad_id" = $1  [["car_ad_id", 149]]
    Traceback (most recent call last):
           12: from bin/rails:4:in `<main>'
           11: from bin/rails:4:in `require'
           10: from /home/.rvm/gems/ruby-2.5.0/gems/railties-4.2.10/lib/rails/commands.rb:17:in `<top (required)>'
            9: from /home/.rvm/gems/ruby-2.5.0/gems/railties-4.2.10/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
            8: from /home/.rvm/gems/ruby-2.5.0/gems/railties-4.2.10/lib/rails/commands/commands_tasks.rb:68:in `console'
            7: from /home/.rvm/gems/ruby-2.5.0/gems/railties-4.2.10/lib/rails/commands/console.rb:9:in `start'
            6: from /home/.rvm/gems/ruby-2.5.0/gems/railties-4.2.10/lib/rails/commands/console.rb:110:in `start'
            5: from (irb):14
            4: from /home/.rvm/gems/ruby-2.5.0/gems/activerecord-4.2.10/lib/active_record/relation/delegation.rb:99:in `method_missing'
            3: from /home/.rvm/gems/ruby-2.5.0/gems/activerecord-4.2.10/lib/active_record/relation/delegation.rb:132:in `method_missing'
            2: from /home/.rvm/gems/ruby-2.5.0/gems/activerecord-4.2.10/lib/active_record/relation/delegation.rb:132:in `public_send'
            1: from /home/.rvm/gems/ruby-2.5.0/gems/activerecord-4.2.10/lib/active_record/relation/delegation.rb:132:in `max'
    TypeError (no implicit conversion of Symbol into Integer)

如果您能帮我理解这里的问题,以及如何解决问题,我将不胜感激。

1 个答案:

答案 0 :(得分:3)

使用maximum代替max

mycar.bids.maximum(:bid_value)