我的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"
)
答案 0 :(得分:1)
您可能希望在以下方面更多地执行此操作:
user = User.create(#stuff#)
user.user_prices.create(#stuff#)
假设有一个has_many关系。