NoMethodError,未定义的方法"bid"



我一直试图从rails对象上的控制器中调用一个helper方法,但我仍然收到这个错误。这是我所有的代码。

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)

有人能告诉我我的代码是错误的还是方法不正确吗?感谢

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

您对控制器上的方法有错误的理解,您正试图在对象上调用控制器方法,但您不能这样做。AuctionsController上的方法是Controllers的一部分,而不是Class的一部分。如果您想向Model类添加操作,则必须将它们写入AuctionModel

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

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

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

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

最新更新