如何在rails 3中编写此记录搜索

时间:2012-01-24 11:00:22

标签: ruby-on-rails-3 activerecord models

 #find the most recent news item for a specific locale
  def self.find_most_recent_news_for_locale

    first(:include => :news_item_detail,:conditions => ["news_items.created_at= ? AND  news_item_details.locale = ?",  maximum(:created_at), I18n.locale])
  end

模特

class NewsItem < ActiveRecord::Base

has_one :news_item_detail

end

class NewsItemDetail < ActiveRecord::Base

belongs_to :news_item

end

1 个答案:

答案 0 :(得分:1)

在Rails 3中,您应该使用where方法创建条件:

def self.find_most_recent_news_for_locale
  where("news_items.created_at = ? AND news_item_details.locale = ?",
    maximum(:created_at), 
    I18n.locale).includes(:news_item_details).first
end

您可能希望将Railscast的episode #202视为快速教程。