Joe
Joe

Reputation: 293

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?

Upvotes: 0

Views: 189

Answers (2)

Hieu Pham
Hieu Pham

Reputation: 6707

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

Upvotes: 1

Kevin
Kevin

Reputation: 162

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.

Upvotes: 1

Related Questions