0

当我尝试访问模型 NewsItem.published 中的符号时,我收到了 NoMethodError。

调用的控制器是显示:

class NewsItemsController < ApplicationController
  def index
    @news_items = NewsItem.published
  end

  def show
    @news_item = NewsItem.find(params[:id])
  end

end

错误是:

undefined method `published' for #<Class:0x105ca3fe0>

vendor/rails/activerecord/lib/active_record/base.rb:1541:in `method_missing_without_paginate'
vendor/plugins/will_paginate/lib/will_paginate/finder.rb:93:in `method_missing'
app/controllers/news_items_controller.rb:3:in `index'

型号代码为:

class NewsItem < ActiveRecord::Base
  belongs_to :news_category
  validates_presence_of :title, :summary, :body, :release_at

  scope :published, :conditions => ["news_items.release_at > ?", Time.now]
  scope :homepage_published, :conditions => ["news_items.release_at > ?", Time.now], :limit => 3
end

我已经合并了另一个开发人员代码,所以我想知道是否可能缺少一些方法声明......

任何帮助或建议将不胜感激。谢谢。

编辑 - 在模型代码中添加了 lambda:

class NewsItem < ActiveRecord::Base
  belongs_to :news_category
  validates_presence_of :title, :summary, :body, :release_at


  scope :published, lambda { 
    where(["news_items.release_at > ?", Time.now])
  }  
  scope :homepage_published, lambda { 
    where(["news_items.release_at > ?", Time.now])
  }  
  #scope :published, :conditions => ["news_items.release_at > ?", Time.now]
  #scope :homepage_published, :conditions => ["news_items.release_at > ?", Time.now], :limit => 3
end

值得一提的是,这个应用程序处于版本控制之下,在合并了添加新闻项目代码的开发人员的更改后,我运行了:

bundle exec rake db:migrate
4

1 回答 1

1

用这个:

scope :published, lambda { 
  where(["news_items.release_at > ?", Time.now])
}
于 2013-04-02T17:44:12.570 回答