how to insert into multiple tables in rails

廉价感情. 提交于 2019-12-08 00:44:57

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/1673433/how-to-insert-into-multiple-tables-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!