开发者

how to add a entry to tables with relationships?

I have 2 models, Users & Accounts. They are in one-to-many relationship, i.e. each accounts have many users.

Accounts

company_id    company_name    company_website

Users

user_id       user_name     password     company_id    email

How can I add these entries to database using ActiveRecord? Supposed I don't is the company existed in the database when I add a new entry.

Name            Email               Password            Company
-----------------------------------------------------------------------------
Albert   开发者_StackOverflow中文版       albert@abc.com      123456              ABC Company
Betty           betty@abc.com       234567              ABC Company
Carmen          carmen@example.com      765432              XXX Company
David           david@abc.com       654321              ABC Company


Add this to your db/seed.rb file:

Account.transaction do 
  [
    ["Albert", "albert@abc.com", "123456", "ABC Company"],
    ["Betty",  "betty@abc.com", "234567", "ABC Company"]
  ].each do |record|
    company = find_or_create_by_company_name(record[3])
    company.users.create(:user_name => record[0].downcase, 
                         :email     => record[1], 
                         :password  => record[2])
  end
end

Run the following rake task:

rake db:seed
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜