Rails 从另一个模型的控制器更新一个模型中的数据

发布于 2024-10-31 05:33:16 字数 371 浏览 4 评论 0原文

我有一个具有 billing_id 的用户模型。我有一个订单模型,它通过支付网关运行交易,该网关返回一个账单 ID,我想将其保存到用户模型的 billing_id 列中。我认为我混淆了 MVC 架构的基础知识。

我的印象是 UsersController 和 OrdersController 更新各自表的数据。这是否意味着如果我从 OrdersController 返回了某些内容(例如账单 ID),则没有其他方法可以将该账单 ID 保存到用户模型中的 billing_id 列中?如果这是非常初级的,谢谢并抱歉。 :)

另外,我认为一个可能的解决方案可能是以某种方式通过ApplicationsController将返回值传递到UsersController中以保存到User表中。这可能吗?

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.

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. :)

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦途 2024-11-07 05:33:16

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

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

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),否则它们将无法相互了解。这称为外键。

当以这种方式设置时,您可以通过以下操作获取用户:

User.find(1).orders

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

Orders.find(1).user

我希望这会有所帮助。

编辑:

Orders.find(ORDER_ID).user.update_attributes(:billing_id => BILLING_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

Your models will then look like:

class User < ActiveRecord::Base
  has_many :orders
end

class Order < ActiveRecord::Base
  belongs_to :user
end

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

I hope this helps.

EDIT:

Orders.find(ORDER_ID).user.update_attributes(:billing_id => BILLING_ID)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文