问题
I currently have a site with Users, Meals, and Orders tables.
- Users table holds the User information
- Meals table holds the Meal name, description, img(url)
I am currently displaying the Meals using an iteration:
<% @meals.each do |meal| %>
<%= image_tag(meal.img, alt: meal.name) %>
<span class="mealname"><%= meal.name %></span>
<p><%= meal.description %><p>
<div class="qty">
INPUT FOR ORDER QTYS HERE
</div>
<% end %>
- Orders table holds the qty's that the user wants for each Meal
Orders migration for reference:
t.belongs_to :user
t.integer :total_meals, null: false, default:"0"
t.integer :meal1, null: false, default: "0"
t.integer :meal2, null: false, default: "0"
etc..
Before I was not using an iteration and had the respective meal1, meal2, etc matching up to the Meals in the HTML layout.
This obviously can be done better, however considering I need the Meals information to be able to be updated dynamically (I want to use the iteration above), How should I go about dealing with this?
But also... if I use another table, how would I possibly be able to implement that into the iteration and populate correctly?
I could add a 'qty' column to the Meals table and make it belong_to :user, but that is also obviously bad practice and will get really messy really quick.
回答1:
If you want to store the information something like:
Order has meal 1, meal 2 and meal 3 and order belongs to User 1
Then you should have the right associations among these 3 models. User
, Meal
and Order
One Order
can have many meals, and one Meal
can belong to many orders, So Order
and Meal
will have many-to-many association
.
And an Order
will belong to
a User
Solution:
Change your Order
model to:
t.belongs_to :user
Add a fourth model, you can name it Quantity
:
t.belongs_to :order
t.belongs_to :meal
t.integer :quantity
Now let's say User A, selects 2 units of Meal A, 3 units of Meal B, you will create an order A, for this user, and Order A will have two entries in Quantity
model containing the info of meal id and their respective quantities.
Update: Models will look like this:
Order.rb
belongs_to :user
has_many :quantities
has_many :meals, through: :quantities
Quantity.rb
belongs_to :order
belongs_to :meal
Meal.rb
has_many :quantities
has_many :orders, through: :quantities
User.rb
has_many :orders
Then, if you want to get the total number of orders one meal has get, you can get it by:
meal.orders.count
and if you want to get all the meals one order has and their quantities:
order.quantities.each do |record|
record.meal.name # for name of associated meal
record.quantity # for quantity of meal
end
来源:https://stackoverflow.com/questions/53016976/rails-5-database-design-with-iterations