Rails从另一个模型的控制器更新一个模型中的数据 [英] Rails Updating Data in one Model from another Model's Controller

查看:94
本文介绍了Rails从另一个模型的控制器更新一个模型中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有billing_id的用户模型。我有一个订单模型,该模型通过付款网关运行交易,该网关返回我想保存到用户模型上billing_id列中的账单ID。我想我把MVC架构的基础混为一谈。

I have a User model that has billing_id. I have Order model that runs transactions with a payment gateway which returns a billing id I'd like to save into the billing_id column on the User model. I think I am getting the basics of MVC architecture mixed up.

我的印象是,UsersController和OrdersController会更新各自表的数据。这是否意味着如果我从OrdersController返回了一些信息(例如,帐单ID),没有其他方法可以将该帐单ID保存到用户模型中的billing_id列中?感谢和抱歉,如果这是非常基本的。 :)

I am under the impression that UsersController and OrdersController update data of their respective tables. Does that mean that if I have something returned from OrdersController such as a billing id, there is no other way of saving that billing id into a billing_id column in User model? Thanks and sorry if this is extremely rudimentary. :)

此外,我认为可能的解决方案可能是以某种方式通过ApplicationsController将返回值传递给UsersController并保存到User表中。

Also, I thought a possible solution might be to somehow pass in the return value via ApplicationsController into UsersController to save into User table. Is this possible?

推荐答案

您的用户订单表应该有一个user_id实例,因为一个用户可以有多个订单。

Your user orders table should have an instance of user_id, as a user can have multiple orders.

您可以通过创建迁移来做到这一点:

You can do this by creating a migration:

rails g migration add_user_id_to_orders order_id:integer
rake db:migrate

您的模型将如下所示:

class User < ActiveRecord::Base
  has_many :orders
end

class Order < ActiveRecord::Base
  belongs_to :user
end

您需要以下两者之间的链接两者(order_id),否则它们将彼此不了解。这就是外键。

You need a link between the two (order_id) otherwise they would have no knowledge of each other. This is known as a foreign key.

通过这种方式设置事物后,您可以通过以下操作获得用户:

When things are set up this way, you can get the users by doing:

User.find(1).orders

您可以通过执行以下操作从订单中找到用户信息:

And you can find the user information from an order by doing:

Orders.find(1).user

我希望这会有所帮助。

编辑:

Orders.find(ORDER_ID).user.update_attributes(:billing_id => BILLING_ID)

这篇关于Rails从另一个模型的控制器更新一个模型中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆