0

我一直在尝试从我的控制器在 rails 对象上调用辅助方法,但我继续收到此错误。这是我所有的代码。

class AuctionsController < ApplicationController
  helper_method :bid

  def bid
    @auction = @auction.update_attribute(:current_price == :current_price + 1.00)
  end

看法

<%= link_to("Bid", @auction.bid(auction) )%>

堆栈跟踪

Started GET "/auctions" for 127.0.0.1 at 2014-11-11 05:46:16 -0600
Processing by AuctionsController#index as HTML
  Auction Load (1.7ms)  SELECT "auctions".* FROM "auctions"
  Rendered auctions/index.html.erb within layouts/spacelab (199.7ms)
Completed 500 Internal Server Error in 234ms

ActionView::Template::Error (undefined method `bid' for nil:NilClass):
    26:     <h3, class="textcolor"><%= auction.description %></h3><br />
    27:     <h3, class="textcolor"><%= auction.start_time.strftime("Opens on %B %d on %I:%M %p") %></h3><br />
28:     <h3, class="textcolor"><%= auction.end_time.strftime("Closes on %B %d on %I:%M %p") %></h3><br />
29:     <%= link_to("Bid", @auction.bid(auction) )%>
30: 
31:         <%= link_to 'Show', auction, class: "btn btn-primary btn-lg btn-block" %>
32:         
  app/views/auctions/index.html.erb:29:in `block in _02d262c45abda05ea87ddc9c2c9ec185'
  app/views/auctions/index.html.erb:16:in `_02d262c45abda05ea87ddc9c2c9ec185'


      Rendered /Users/claymccullough/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.1.6/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (1.0ms)
  Rendered /Users/claymccullough/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.1.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (0.8ms)
  Rendered /Users/claymccullough/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.1.6/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb within rescues/layout (92.3ms)

谁能告诉我我的代码是错误的还是方法不正确?谢谢

编辑请在下面查看我的答案,这是我真正的问题...

4

2 回答 2

2

首先,错误消息ActionView::Template::Error (undefined method bid for nil:NilClass)意味着您正在尝试对bid不存在的对象()调用方法( @auction)。此外,@auction.bid(auction)从语义和代码阅读的角度来看,该位对我来说也不好看,但我不知道您到底要做什么。

如果您向我们展示您的其余部分,AuctionsController我们将能够告诉您更多关于哪里出了问题。

于 2014-11-11T11:57:07.457 回答
2

你对控制器上的方法有误解,你试图在一个对象上调用控制器方法,你不能那样做。AuctionsController 上的方法是 Controllers 的一部分,而不是 Class 的一部分,如果要向 Model 类添加操作,则必须在Auction Model中编写它们

正确调用您的控制器,将@auction 作为参数传递

<%= link_to("Bid", @auction )%>
于 2014-11-11T12:01:33.617 回答