2012-03-05 82 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