你能告诉我一种以更好的方式编写这段代码的方法吗?
User.create do |user|
user.email = data['email']
user.password = Devise.friendly_token
user.facebook_uid = data['facebook_uid']
user.first_name = data['first_name']
user.last_name = data['last_name']
user.gender = data['gender']
user.timezone = data['timezone']
user.birthday = data['birthday']
user.link = data['link']
user.locale = data['locale']
user.picture_url = 'https://graph.facebook.com/' + data['facebook_uid'] + '/picture?type=large'
user.fb_access_token = access_token
end
答案 0 :(得分:2)
hash['picture_url'] = something
User.create(hash)
答案 1 :(得分:0)
ActiveRecord的create方法可以获取属性的哈希值。由于您的哈希键完全匹配访问器方法,因此您可以在设置数据['picture_url']后以与之前相同的方式传入User.create(哈希)。 Tass的答案基本上是正确的,但要更准确地匹配您的代码:
data['picture_url'] = 'https://graph.facebook.com/' + data['facebook_uid'] + '/picture?type=large'
User.create(data)
答案 2 :(得分:0)
解决方案1
User.create do |user|
data.each do |k, v|
user.send("#{k}=", v) if User.columns_hash.has_key?(k)
end
user.fb_access_token = access_token
user.password = Devise.friendly_token
user.picture_url = "https://graph.facebook.com/%s/picture?type=large" %
data['facebook_uid']
end
解决方案2
hash = {}
data.each do |k, v|
hash[k]= v if User.columns_hash.has_key?(k)
end
hash['fb_access_token'] = access_token
hash['password'] = Devise.friendly_token
hash['picture_url'] = "https://graph.facebook.com/%s/picture?type=large" %
data['facebook_uid']
User.create(hash)