希望這不是一個重複的問題,因爲我花了幾周時間搜尋StackOverflow尋找答案,還沒有找到解決我的問題的方法。如何避免ActiveRecord_Relation未定義的方法`id'?
我有一個Ruby on Rails API(Ruby 1.9.3,Rails 4.0.0),並使用ActiveRecord與我們的數據庫交互。當請求檢索當前計劃的橫幅時,它完美地工作。當沒有橫幅計劃,然而,500響應經歷:
undefined method `id' for #\u003cBanner::ActiveRecord_Relation:0x0000000628fba8\u003
我的理解是,這是因爲正在嘗試固有的「ID」的方法是建立在「無」,這是從數據庫查詢結果當沒有找到合格的記錄時。我如何優雅地處理這種情況,以便不會遇到500錯誤,以便我可以向請求者返回更禮貌的響應?
這裏是我的控制器:
class BannersController < ApplicationController
load_and_authorize_resource
respond_to :json
# Look to see if any banners should be showing right now
def current
@banner = Banner.current
end
end
這裏是我的模型:
class Banner < ActiveRecord::Base
self.table_name = 'Banner'
self.primary_key = :BannerID
alias_attribute :name, :FriendlyName
alias_attribute :banner_html, :BannerHtml
alias_attribute :banner_image, :BannerImage
alias_attribute :start_date, :StartDate
alias_attribute :end_date, :EndDate
alias_attribute :is_active, :IsActive
alias_attribute :is_removed, :IsRemoved
alias_attribute :start_date_time, :StartDateTime
alias_attribute :end_date_time, :EndDateTime
alias_attribute :hidden_text, :HiddenText
alias_attribute :hidden_background_color, :HiddenBackgroundColor
# This returns nil if no banner is scheduled, which then causes the view to return a 500 response because it tries to invoke an "id" method
scope :current, -> { Banner.where("StartDateTime <= ? AND EndDateTime >= ? AND IsActive=1 AND IsRemoved=0 AND BannerType=1", Time.now.to_s(:db), Time.now.to_s(:db)).first }
end
注:我一直在使用.find_by嘗試和也嘗試不使用。第一,但似乎仍不能找到對此的解決方案。
這是我的觀點:
json.extract! @banner, :id, :banner_html, :banner_image, :hidden_text, :hidden_background_color
json.request_id request.uuid
數據庫表 「旗」 有 「BannerID」 的主鍵。
感謝所有誰花時間來看看這個。我花了數不清的時間閱讀和嘗試一切,以彌補這種情況,但無濟於事。
嘗試改變':id'到':在'json.extract banner_id''線 – Pavan
什麼是'ActiveRecord_Relation'? – engineersmnky