2012-03-05 22 views
1

我在當前的Rails應用程序中處理棘手的問題。在我的應用程序用戶分享照片。照片可以與一個城市相關聯,所以City has_many :photos。我希望用戶能夠使用自動填充和自然語言語法將他們的照片與城市相關聯。即:紐約,紐約或法國巴黎。Rails:通過虛擬屬性查找或創建

我想做到這一點與自動完成的文本框,這樣,如果用戶鍵入「雅典」,他們將看到一個列表:

Athens, Greece 
Athens, GA 

...如果這個人其實是想「雅典,德克薩斯州「他們可以簡單地輸入,它會創建一個新的城市記錄。

我的城市模型有字段name, state, country。州和國家是2個字母的郵政編碼(我使用卡門來驗證它們)。我有一個名爲full_name的虛擬屬性,其中爲所有其他城市返回「城市,州代碼」(如紐約,紐約州)和「城市,國家名稱」(如法國巴黎)。

def full_name 
    if north_american? 
     [name, state].join(', ') 
    else 
     [name, Carmen.country_name(country)].join(', ') 
    end 
end 

def north_american? 
    ['US','CA'].include? country 
end 

我的問題是,讓文本字段工作,我怎樣才能創建一個可以接受與城市名稱以及州代碼或國家名稱的字符串,找到或創造紀錄一個find_or_create方法?


更新

通過Kandada的回答啓發我想出了一點點不同:

def self.find_or_create_by_location_string(string) 
    city,second = string.split(',').map(&:strip) 
    if second.length == 2 
    country = self.country_for_state(second) 
    self.find_or_create_by_name_and_state(city, second.upcase, :country => country) 
    else 
    country = Carmen.country_code(second) 
    self.find_or_create_by_name_and_country(city, country) 
    end 
end 

def self.country_for_state(state) 
    if Carmen.state_codes('US').include? state 
    'US' 
    elsif Carmen.state_codes('CA').include? state 
    'CA' 
    else 
    nil 
    end 
end 

這搖擺我的規格現在,所以我覺得我的問題就解決了。

回答

2
class Photo < ActiveRecord::Base 

    attr_accessor :location 

    def self.location_hash location 
    city,state,country = location.split(",") 
    country = "US" if country.blank? 
    {:city => city, :state => state, :country => :country} 
    end 

end 

現在你可以「find_or_create_by_ *」

Photo.find_or_create_by_name(
    Photo.location_hash(location).merge(:name => "foor bar") 
) 
+0

這不正是* *我一直在尋找,但您啓發了我,我想我找到了一個可行的解決方案。我會將其附加到問題以供參考。 – Andrew 2012-03-06 01:27:32