如何为用户分配某些种子数据?

时间:2011-10-31 01:00:38

标签: ruby-on-rails ruby-on-rails-3

我的seeds.rb文件中包含以下数据:

users = User.create([
    {
      :email => 'user1@email.com', 
      :password => 'test', 
      :password_confirmation => 'test'
    },
    {
      :email => 'user2@email.com',
      :password => 'test',
      :password_confirmation => 'test'
    }
    ]) 
puts 'Users added'

UserPrice.create([
  {
    # assign user 1
    :product_name => "Great Value Vitamin D Whole Milk",
    :price => '3.81',
    :purchase_date => Date.strptime("08/25/2011", "%m/%d/%Y"),
    :store => "New York"},
  {
    #assign user 2
    :product_name => 'Eggs',
    :price => '2.78',
    :purchase_date => Date.strptime("08/25/2011", "%m/%d/%Y"),
    :store => "New York"
  }
])
puts 'Added Prices'

如何将合法用户分配到我的seeds.rb中的UserPrices

注意:我尝试:user => users.first,但这不起作用。


工作代码:

user1 = User.create(:email => 'user1@email.com', :password => 'qweasd', :password_confirmation => 'qweasd')
user2 = User.create(:email => 'user2@email.com',:password => 'qweasd',:password_confirmation => 'qweasd')

user1.user_prices.create(
    :product_name => "Great Value Vitamin D Whole Milk",
    :price => '3.81',
    :purchase_date => Date.strptime("08/25/2011", "%m/%d/%Y"),
    :store => "New York"
    )
user2.user_prices.create(
    :product_name => 'Eggs',
    :price => '2.78',
    :purchase_date => Date.strptime("08/25/2011", "%m/%d/%Y"),
    :store => "New York"
    )

1 个答案:

答案 0 :(得分:1)

您可能希望在以下方面更多地执行此操作:

user = User.create(#stuff#)
user.user_prices.create(#stuff#)

假设有一个has_many关系。

相关问题