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

元气小坏坏 提交于 2019-12-03 22:47:17

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