Joe Joe - 6 months ago 9
Ruby Question

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?

Answer

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