出现相同的Ruby字符串不相等,为什么?

时间:2017-03-10 14:10:23

标签: ruby-on-rails ruby

我正在导入CSV并使用ActiveRecord创建行。 CSV是:

first_name,middle_name,last_name,degrees,email,induction_year (ie 2017),"induction_type (options: alumni, associate, faculty, honorary, student)"
John,Middle,Doe,"BA, MPH",test@test.com,2017,alumni

我的导入方法如下所示:

def import
  CSV.foreach(@file.path, headers: true, header_converters: lambda {|field| field.partition(" ").first }, col_sep: ',') do |row|
    member_params = row.to_hash
    Member.create!(member_params)
  end
end

但它抛出了ActiveModel::UnknownAttributeError: unknown attribute 'first_name' for Member.编辑:会员我可以像Member.create!(first_name: 'test')

那样创建会员,这不是问题

打开一个撬,我得到这个反馈:

[1] pry(#<InducteesUpload>)> member_params
=> {"first_name"=>"John",
"middle_name"=>"Middle",
"last_name"=>"Doe",
"degrees"=>"BA, MPH",
"email"=>"test@test.com",
"induction_year"=>"2017",
"induction_type"=>"alumni"}
[2] pry(#<InducteesUpload>)> member_params.keys.first == "first_name"
 => false
[3] pry(#<InducteesUpload>)> member_params.keys.first.encoding
=> #<Encoding:UTF-8>

添加更多:

[1] pry(#<InducteesUpload>)> member_params.keys
=> ["first_name",
  "middle_name",
  "last_name",
  "degrees",
  "email",
  "induction_year",
  "induction_type"]

[2] pry(#<InducteesUpload>)> member_params["first_name"] = "test"
=> "test"
[3] pry(#<InducteesUpload>)> member_params
=> {"first_name"=>"John",
 "middle_name"=>"Middle",
 "last_name"=>"Doe",
 "degrees"=>"BA, MPH",
 "email"=>"test@test.com",
 "induction_year"=>"2017",
 "induction_type"=>"alumni",
 "first_name"=>"test"}

这对会员来说不是问题,你可以用上面的怪异看到。但是如果你真的想要发帖的话会发布。

这里揭示了问题:

[6] pry(#<InducteesUpload>)> member_params.keys.first.bytes
=> [239, 187, 191, 102, 105, 114, 115, 116, 95, 110, 97, 109, 101]
[7] pry(#<InducteesUpload>)> "first_name".bytes
=> [102, 105, 114, 115, 116, 95, 110, 97, 109, 101]

2 个答案:

答案 0 :(得分:2)

我打赌unicode魔法。比较member_params.keys.first.bytes"first_name".bytes。你可能会发现一个不同之处。

Unicode有很多看起来相似的符号,但彼此并不相同。

答案 1 :(得分:0)

我相信你的字符串和符号之间存在冲突,因为你的哈希键。请按照here提及Member.create!(member_params.with_indifferent_access)