1

我在当前的 Rails 应用程序中遇到了一个棘手的问题。在我的应用中,用户分享照片。照片可以与城市相关联,因此City has_many :photos. 我希望用户能够使用自动完成和自然语言语法将他们的照片与城市相关联。即:纽约,纽约或巴黎,法国。

我想用一个自动完成的文本框来做到这一点,这样如果用户输入“雅典”,他们会看到一个列表:

Athens, Greece
Athens, GA

......如果这个人真的想要“雅典,德克萨斯”,他们可以简单地输入它,它会创建一个新的城市记录。

我的城市模型有田地,name, state, country. State 和 Country 是 2 个字母的邮政编码(我使用 Carmen 来验证它们)。我有一个名为的虚拟属性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

这现在正在改变我的规格,所以我认为我的问题已经解决了。

4

1 回答 1

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")
)
于 2012-03-05T23:52:31.953 回答