Ruby 2.0,Rails 4.1.0,sQlite3。我必须在哈希中创建参数以添加到我的数据库。我有yaml文件和模型:
class User < ActiveRecord::Base
has_many :tweets
accepts_nested_attributes_for :tweets
end
class Tweet < ActiveRecord::Base
belongs_to :user
end
我有15个用户。尝试运行此代码
UsTw_model_params = {user: []}
count_of_users = seeds_yml["users"].length - 1
for i in 0..count_of_users do
UsTw_model_params[:user][i] = {}
UsTw_model_params[:user][i][:name] = seeds_yml["users"][i]["name"]
UsTw_model_params[:user][i][:email] = seeds_yml["users"][i]["email"]
UsTw_model_params[:user][i][:password] = seeds_yml["users"][i]["password"]
UsTw_model_params[:user][i][:avatar] = seeds_yml["users"][i]["avatar"]
UsTw_model_params[:user][i][:tweets_attributes] = []
if seeds_yml["users"][i].has_key?(:tweets)
count_of_tweets = seeds_yml["users"][i]["tweets"].length - 1
for j in 0..count_of_tweets do
UsTw_model_params[:user][i][:tweets_attributes][j] = {}
UsTw_model_params[:user][i][:tweets_attributes][j][:post] = seeds_yml["users"][i]["tweets"][j]["post"]
UsTw_model_params[:user][i][:tweets_attributes][j][:created_at] = seeds_yml["users"][i]["tweets"][j]["created_at"]
end
end
end
User.create(UsTw_model_params[:user])
并收到错误 ActiveRecord :: UnknownAttributeError:unknown属性:user
什么事?
答案 0 :(得分:1)
首先,在Ruby中以大写字母开头的任何内容都被视为常量。 重新分配常量会导致警告。 具体做法是:
UsTw_model_params = {user: []} # is a constant!
示例:
class User
module Huggable
TAU = 2 * PI
变量{@ 3}}应该是蛇形的,例如:
user_tweet_params
其次,您可以留下for
个循环。 Ruby有更好的方法在数组和其他可用内容中循环,例如map
,each
等。
# Loop though seeds_yml["users"] and create a new array
user_tweet_params = seeds_yml["users"].map do |user|
# with_indifferent_access allows us to use symbols or strings as keys
user = user.with_indifferent_access
user.slice!(:name, :email, :password, :avatar, :tweets)
# Does the user have tweets?
# We use try(:any?) incase user["tweets"] is nil
if user[:tweets].try(:any?)
# Take the tweets and nest then under tweet_attributes
user[:tweet_attributes] = user.tweets.map do |tweet|
tweet.with_indifferent_access.slice!(:post, :created_at)
end
end
# remove the original tweets
user.delete(:tweets)
# return user
user
end