how to insert into multiple tables in rails

2019-05-22 20:19发布

i am trying to insert into multiple tables using rails.. i have a table called users and services. when i create a user the user details should go into users and a service name and userid should go into services table. Any help would be greatly appriciated.

Thanks.

2条回答
地球回转人心会变
2楼-- · 2019-05-22 20:26

You can also use accept_nested_attributes_for:

class User < ActiveRecord::Base
  has_one :service
  accepts_nested_attributes_for :service
end

User.create(:name => "Example User", :service_attributes => {:name => "Example Service"})

Filling in the service_attributes hash is made simple with nested forms.

查看更多
SAY GOODBYE
3楼-- · 2019-05-22 20:36

You can add a callback to create a new service when a user is created.

class User < ActiveRecord::Base
    def after_create
        Service.create!(:name => 'my_service_name', :user_id => self.id)
    end
end

The after_create method is triggered after a new user creation. So a new service will be created every time you create a new user.

You can find more informations about the callbacks on the Rails Guides.

查看更多
登录 后发表回答