简体   繁体   English

在Rails中设置可自动更新的has_many关联

[英]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. 我正在将Sinatra应用程序迁移到Rails,并且遇到了一些麻烦,因为我是Rails方面的新手。

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. 我已经在模型中设置了has_many和belongs_to关联,并在订单中添加了一个user_id关联列。

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. 如果您正确设置了模型,则用户应具有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. 只要新订单正确存储了user_id,所有订单都应正常工作。

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! 如果order不属于用户,则order.user为nil,因此如果不为order.user ,则order为用户,并且user至少有1个订单!

Otherwise if you want to check a user has any order or not, just do this: 否则,如果您要检查用户是否有任何订单,只需执行以下操作:

user.orders.count > 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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