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.
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.
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.
精彩评论