【问题标题】:(Ruby on Rails) Help to add Hash to DB(Ruby on Rails)帮助将哈希添加到数据库
【发布时间】:2014-05-18 14:21:45
【问题描述】:

Ruby 2.0、Rails 4.1.0、sQlite3。我必须在 Hash 中创建参数以添加到我的数据库。我有 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 attribute: user

怎么了?

【问题讨论】:

    标签: ruby ruby-on-rails-4 hash yaml


    【解决方案1】:

    首先,在 Ruby 中以大写字母开头的任何内容都被视为常量。 重新分配常量会导致警告。 具体来说:

    UsTw_model_params = {user: []} # is a constant!
    

    例子:

    class User
    module Huggable
    TAU = 2 * PI
    

    变量应该by convention 在蛇形盒中,例如:

    user_tweet_params
    

    其次,您可以留下 for 循环。 Ruby 有更好的方法在数组和其他枚举中循环,例如 mapeach 等。

    # 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
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    • 2013-03-02
    • 2011-04-17
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 1970-01-01
    相关资源
    最近更新 更多