[英]Call controller action from one application to another in Rails
I have two applications that interact with each other. 我有两个相互交互的应用程序。 I need to create a database instance of a model in the second application that is created in the first.
我需要在第一个创建的第二个应用程序中创建模型的数据库实例。 The below code works only when I call the method in the second application after creating
User
instance and saving it. 以下代码仅在创建
User
实例并保存后在第二个应用程序中调用该方法时有效。
app1_service.rb app1_service.rb
def send_user_data
json_data = {}
user = User.last
json_data[:app1_user_id] = user.id
json_data[:user_name] = user.name
render json_data
end
app2_service.rb app2_service.rb
def create_user
response = App2Service.post( '/services/app1_service/send_user_data.json', query: { request: { authenticate: {auth_key: "#{APP_CONFIG[:auth_key]}"} } } )
User.create(app1_user_id: response['app1_user_id'], user_name: response['user_name'])
end
What I want to do is to create the User
instance in app2
database whenever that user
is created in app1
. 我想要做的是创造
User
的情况下app2
每当数据库user
在创建app1
。 So I tried like this: 所以我尝试这样:
users_controller.rb users_controller.rb
def create
if @user.save
Services::App1Controller.send_user_data(user)
end
app1_service.rb app1_service.rb
def self.send_user_data(user)
#Here I am not able to figure out how to call the action from the controller in the other application
end
What changes should I make so that it works as per the requirement? 我应该进行哪些更改才能使其按要求工作?
This case you should call app2 API in order to create a User on app2 database, something like: /services/app2_service/send_user_data.json
. 在这种情况下,您应该调用app2 API才能在app2数据库上创建用户,例如:
/services/app2_service/send_user_data.json
。 You should also create this API on app2. 您还应该在app2上创建此API。
If you really need this data synchronized, it's recommended to use PostgreSQL Multi-Master Replication to keep both databases with the same data, or Kafka events. 如果确实需要同步这些数据,建议使用PostgreSQL多主复制来使两个数据库保持相同的数据或Kafka事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.