我有兩個模型,它們都有has_and_belongs_to_many
彼此關聯。Rails 5 Active Record has_and_belongs_to_many
訂購
class Order < ApplicationRecord
# Has multiple related rates.
has_and_belongs_to_many :rates
率
class Rate < ApplicationRecord
has_and_belongs_to_many :orders
率包含給定日期的貨幣數據,而訂單包含的最後期限。根據訂單的截止日期,我有一份工作,創建並提取(today..deadline) - 1年之間的所有日期。
工作
def perform(order_record)
(all_dates << history_weeks).flatten!
all_dates.each do |date|
r = Rate.find_by(date: date)
if r == nil
r = Rate.new(date: date)
r.save
end
q = r.update(orders << order_record)
end
現在的事情是,爲有史以來第一次下令我創造,一切順利,該協會已正確,這樣我可以通過@order.rates
訪問率。第二,每一個訂單,我創建沒有做到這一點,儘管登陸以下,但只有一次:
Rate Load (0.0ms) SELECT "rates".* FROM "rates" INNER JOIN "orders_rates" ON "rates"."id" = "orders_rates"."rate_id" WHERE "orders_rates"."order_id" = ? ORDER BY "rates"."id" ASC LIMIT ? [["order_id", 4], ["LIMIT", 1]]
我在做什麼錯在那裏?
編輯:
作業名爲在orders_controller:
def create
@order = Order.new(order_params)
@order.user = User.find(current_user)
respond_to do |format|
if @order.save
GetCurrencyHistoryJob.perform_now(@order)
format.html { redirect_to @order, notice: 'Order was successfully created.' }
format.json { render :show, status: :created, location: @order }
else
format.html { render :new }
format.json { render json: @order.errors, status: :unprocessable_entity }
end
end
end
你能後,你所說的工作 –