【问题标题】:ActionView::Template::Error: undefined method `latest' for #<Class:0x007f8b5d07e5c8>ActionView::Template::Error: #<Class:0x007f8b5d07e5c8> 的未定义方法“最新”
【发布时间】:2014-09-17 01:14:21
【问题描述】:

我遇到了一个我无法解决的错误,我知道“get :index”由于某种原因没有连接起来。

StoreControllerTest#test_should_get_index:
ActionView::Template::Error: undefined method latest' for #<Class:0x007f8b5d07e5c8> app/views/store/index.html.erb:7:in _app_views_store_index_html_erb___4260644534451553693_70118269675460'
    test/controllers/store_controller_test.rb:5:in `block in <class:StoreControllerTest>

这是 store_controller_test.rb 的代码

require 'test_helper'

class StoreControllerTest < ActionController::TestCase
  test "should get index" do
    get :index
    assert_response :success
    assert_select '#columns #side a', minimum: 4
    assert_select '#main .entry', 3
    assert_select 'h3', 'Programming Ruby 1.9'
    assert_select '.price', /\$[,\d]+\.\d\d/
  end

end

这里是 index.html.erb 的代码

<% if notice %>
<p id='notice'> <%= notice %> </p>
<% end %>

<h1>Your Pragmatic Catalog</h1>

<% cache ['store', Product.latest] do %>
<% @products.each do |product| %> 
<% cache ['entry', product] do %>
<div class='entry'>
<%= image_tag(product.image_url) %>
<h3><%= product.title %></h3>
<%= sanitize(product.description) %>
<div class='price_line'>
<span class='price'><%= number_to_currency(product.price) %></span>
<%= button_to 'Add to Cart', line_items_path(product_id: product) %>
  </div>
 </div>
  <% end %>
<% end %>
<% end %>

【问题讨论】:

  • 你能发布你的Product 模型吗?

标签: ruby-on-rails methods indexing undefined actionview


【解决方案1】:

没有为Product 类定义latest 方法。您可能的意思是:

Product.last

【讨论】:

  • @BradleyArnott 我的回答有帮助吗?
  • 本书中的错字(Agile Web Dev with Rails 4)?第 105 页。
【解决方案2】:

迟到的答案,但我刚刚遇到了这个。您应该在 app/models/product.rb 中有以下方法

def self.latest
  Product.order(:updated_at).last
end

这是它引用“最新”的地方(Agile Web Development with Rails 4 中的第 104 页)

【讨论】:

    【解决方案3】:

    另外,请确保您的 self.latest 方法放在 Product 类中。在我的情况下这是一个错误,我将方法放在类之外,它引发了一个错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-11
      • 1970-01-01
      • 1970-01-01
      • 2013-04-10
      • 2015-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多