基本上,我想要做的是加入文本欄位而不是像
SELECT country.delivery_time
FROM order, country
WHERE order.country = country.name
到目前為止,我對 Rails 模型的了解是
class Country < ApplicationRecord
validates :name, presence: true
validates :delivery_time, presence: true
end
class Order < ApplicationRecord
validates :country, presence: true
def shipping_time
# want to get the correct country from the DB
if self.country == country.name
country.delivery_time
else
"unavailable"
end
end
end
shipping_time應該回傳連接結果的函式在哪里。我得到的錯誤是
未定義的方法“國家”
我正在使用 Ruby 3.0.3 和 Rails 7.0.0。
uj5u.com熱心網友回復:
打破慣例并使用任何型別的外鍵列實際上非常簡單:
class AddCountryNameToOrders < ActiveRecord::Migration[7.0]
def change
add_column :orders, :country_name, :string
# Some DB's may not allow foreign key constraints
# on non PK columns
add_foreign_key :orders, :countries,
column: :country_name,
primary_key: :name
end
end
class Order < ApplicationRecord
validates :country, presence: true
belongs_to :country,
foreign_key: :country_name,
primary_key: :name
end
class Country < ApplicationRecord
has_many :orders,
foreign_key: :country_name,
primary_key: :name
end
用作primary_key選項的列實際上不必是目標表的 PK。簡單地命名列country會導致名稱沖突,除非您為關聯選擇不同的名稱(并使這變得更加混亂)。
但考慮到域,這是一個非常糟糕的主意。
國家確實會更改名稱——最近的例子是北馬其頓和斯威士蘭。
相反,只需使用普通整數/uuid 外鍵列并使用委托從國家/地區獲取名稱。
class Order < ApplicationRecord
belongs_to :country
delegate :name, to: :country,
prefix: true
end
如果您想對表使用“自然”主鍵而不是代理鍵(例如自動生成的 id),那么 ISO 3166 國家代碼是一個更好的選擇。
uj5u.com熱心網友回復:
所以我最終使用這個joins函式來得到我想要的,
Order.joins("INNER JOIN countries ON orders.country = countries.name")
完整的功能在哪里
def shipping_time
relation = Order.joins("INNER JOIN countries ON orders.country = countries.name")
if 1 == relation.count()
relation[0].delivery_time
else
"unavailable"
end
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/440719.html
標籤:轨道上的红宝石 红宝石 ruby-on-rails-7
下一篇:Ruby將逗號分隔值轉換為陣列
