开发者

how to insert into multiple tables in rails

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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜