我的产品型号包含一些项目

 Product.first
 => #<Product id: 10, name: "Blue jeans" >

我现在从另一个数据集导入一些产品参数,但是名称的拼写不一致。例如,在另一个数据集中,Blue jeans可以拼写为Blue jeans。

我想要产品。find_or_create_by_name("Blue Jeans"),但这将创建一个与第一个几乎相同的新产品。我的选择是什么,如果我想找到和比较小写的名字。

性能问题在这里并不重要:只有100-200个产品,我希望将其作为导入数据的迁移来运行。

什么好主意吗?


当前回答

有几个注释提到了Arel,但没有提供示例。

下面是一个不区分大小写搜索的Arel示例:

Product.where(Product.arel_table[:name].matches('Blue Jeans'))

这种类型的解决方案的优点是它与数据库无关——它将为当前适配器使用正确的SQL命令(匹配将对Postgres使用ILIKE,而对其他一切使用LIKE)。

其他回答

假设您使用mysql,您可以使用不区分大小写的字段:http://dev.mysql.com/doc/refman/5.0/en/case-sensitivity.html

引用SQLite文档:

任何其他字符匹配自身或 它的小写/大写等价(即。 不区分大小写匹配)

...我不知道。但它是有效的:

sqlite> create table products (name string);
sqlite> insert into products values ("Blue jeans");
sqlite> select * from products where name = 'Blue Jeans';
sqlite> select * from products where name like 'Blue Jeans';
Blue jeans

所以你可以这样做:

name = 'Blue jeans'
if prod = Product.find(:conditions => ['name LIKE ?', name])
    # update product or whatever
else
    prod = Product.create(:name => name)
end

不是#find_or_create,我知道,它可能不是很跨数据库友好,但值得一看?

在postgres:

 user = User.find(:first, :conditions => ['username ~* ?', "regedarek"])

如果您正在使用postgres(可能是其他的),我喜欢这个解决方案。

Product.find_by("name ilike 'bLue JEaNS'")

我更喜欢这个,有几个原因。

更清晰的连接到数据库操作->你可以复制粘贴到哪里… 如果您选择添加一个外接符%,这很简单。

另一种选择是

c = Product.find_by("LOWER(name)= ?", name.downcase)