Rails Updating Data in one Model from another Model's Controller

◇◆丶佛笑我妖孽 提交于 2019-12-21 06:27:00

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/5587398/rails-updating-data-in-one-model-from-another-models-controller

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