以不区分大小写的方式预载has_one关联

时间:2019-05-10 09:59:31

标签: elixir mariadb phoenix-framework ecto

我们目前正在从Ruby / Rails / MariaDB迁移到Elixir / Phoenix / MariaDB的过程中,当我在Ecto中预加载关联时遇到一个问题,而ActiveRecord则看不到。

我们在Rails项目中定义了一些关系,这些关系具有string类型的外键(我知道这不是最佳实践)。例如,一个帐户有一个计费计划(在新的Elixir项目中定义):

schema "accounts" do
  field(:name, :string)
  field(:email_address, :string)
  field(:active, :boolean)
  field(:billing_model, :string)
  has_one(:billing_plan, BillingPlan, foreign_key: :name, references: :billing_model)
end

schema "billing_plans" do
  field(:name, :string)
  field(:price, :integer)
end

当大小写不匹配时,例如,如果帐户将Pro存储为billing_model,但是billing_plans表将其存储为pro,则会出现问题。当我尝试这样的预加载关联时:Repo.get(Account, 1234) |> Repo.preload(:billing_plan),Ecto为nil返回billing_plan。而如果案件匹配,Ecto将按预期返回billing_plan

我最初的想法是在数据库中修复此问题,以使案件匹配。但是,随着新示例的出现,这没有用,我意识到这并不是这种关联所独有的问题-我们的架构中有许多类似的关系。这就是为什么我想在更高层次上解决此问题,以便以后不会再次咬我们。理想情况下,定义关联时最好将标志传递给数据库配置或选项。

在解决这个问题之前,有没有人遇到过这个问题?

1 个答案:

答案 0 :(得分:0)

据我了解,由于大写/小写,您的字符串外键不匹配。

如果我没有进行预加载而是建立自己的查询,我无法测试这种情况,那应该是

(from a in Account, join: b in BillingPlan, where: a.billing_model == 1234 and a.billing_model == b.name, select: %{ a | billing_plan: b}) |> Repo.one()

在执行此操作之前,您需要导入Ecto.Query。

我希望它能起作用。