使用Rails 5.如何獲得ActiveRecord而不是ActiveRecord關係?我ahve下面的模型如何取回ACtiveRecord而不是ACtiveRecord關係?
class State < ActiveRecord::Base
belongs_to :country
...
def self.cached_find_us_state_by_name(name)
Rails.cache.fetch("#{name.upcase} US") do
find_us_state_by_name(name)
end
end
# Look up a US state by its full name
def self.find_us_state_by_name(name)
search_criteria = ["upper(states.name) = ? "]
search_criteria.push("states.country_id = countries.id ")
search_criteria.push("countries.iso = 'US' ")
results = State.joins(:country).where(search_criteria.join(' and '),
name.upcase)
end
但是當我使用的方法,啥子我回來是ActiveReocrd關係...
2.4.0 :004 > State.cached_find_us_state_by_name('Ohio')
=> #<ActiveRecord::Relation [#<State id: 3538, name: "Ohio", country_id: 233, iso: "OH">]>
這將在後面cauisng的問題,特別是查找一個項目.. 。
ActiveRecord::AssociationTypeMismatch: State(#70288305660760) expected, got State::ActiveRecord_Relation(#70288290686360)
from /Users/davea/.rvm/gems/[email protected]/gems/activerecord-5.0.1/lib/active_record/associations/association.rb:221:in `raise_on_type_mismatch!'
from /Users/davea/.rvm/gems/[email protected]/gems/activerecord-5.0.1/lib/active_record/associations/belongs_to_association.rb:12:in `replace'
編輯:按所給的建議,我改變了我的方法來
def self.cached_find_us_state_by_name(name)
Rails.cache.fetch("#{name.upcase} US") do
find_us_state_by_name(name)
end
end
# Look up a US state by its full name
def self.find_us_state_by_name(name)
search_criteria = ["upper(states.name) = ? "]
search_criteria.push("states.country_id = countries.id ")
search_criteria.push("countries.iso = 'US' ")
results = State.joins(:country).where(search_criteria.join(' and '),
name.upcase).take
end
但很可惜,我仍然得到一個ActiveRecord ::關係
2.4.0 :011 > State.cached_find_us_state_by_name('Ohio')
=> #<ActiveRecord::Relation [#<State id: 3538, name: "Ohio", country_id: 233, iso: "OH">]>
我編輯了我的問題,以顯示當我嘗試您的建議時發生了什麼。只需添加「.take」?它不工作。 – Dave
Nvm,它確實工作 - 數據被緩存,但是當我退出控制檯並重新加載時,它運行良好。 – Dave