(RubyonRails)帮助向DB添加哈希
Ruby 2.0、Rails 4.1.0、sQlite3。我必须在散列中创建参数以添加到我的数据库中。我有yaml文件和模型:(RubyonRails)帮助向DB添加哈希,ruby,ruby-on-rails-4,hash,yaml,Ruby,Ruby On Rails 4,Hash,Yaml,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 并获取错误ActiveRecord::UnknownAt
class User < ActiveRecord::Base
has_many :tweets
accepts_nested_attributes_for :tweets
end
class Tweet < ActiveRecord::Base
belongs_to :user
end
并获取错误ActiveRecord::UnknownAttributeError:未知属性:用户
怎么了?首先,在Ruby中以大写字母开头的任何东西都被视为常量。 重新指定常数将导致警告。 具体而言:
UsTw_model_params = {user: []} # is a constant!
示例:
class User
module Huggable
TAU = 2 * PI
变量应为蛇形,例如:
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
有关详细信息,请参阅和。感谢您的详细回复
# 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