问题
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