简体   繁体   中英

Setting up a has_many association in Rails that auto-updates

first off, sorry for the noobish question. I'm migrating a Sinatra app to Rails, and having a bit of difficulty with it, since I'm new to the Rails side.

I have two models, User and Order. I've set up a has_many & belongs_to association in the models, and I've added a user_id association column in orders.

But I feel like users should have an association column of some kind too? (Though I'm not sure how to set that up)

Specifically, I want to be able to look at an order, and tell whether the customer has ordered before, as such:

<% @orders.each do |order| %>
<% if (order.user.orders > 1) %> Y<% end %>
<% end %>

But while I can get to the user, I can't then access all orders they're associated with. How do I set up a column to do this, preferably with it updating automatically when a new order is assigned to them?

This is a parent child situation. User is the parent and Order is the child. Parents don't store foreign keys, only the children. If you have the models set up correctly, User should have has_many. Then you should be able to:

user.orders

As long as new orders get the user_id properly stored, all should work correctly.

Your model now is enough:

class Order < ActiveRecord::Base
  belongs_to :user # foreign_key user_id
end

class User < ActiveRecord::Base
  has_many :orders
end

Your view code:

<% @orders.each do |order| %>
  <% if order.user %>
    Y
  <% end %>
<% end %>

Before if order doesn't belong to user, order.user would be nil, so if it is not nil, order belongs to user, and user has at least 1 order!

Otherwise if you want to check a user has any order or not, just do this:

user.orders.count > 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM