Ruby on rails 使用find\u或\u initialize\u by \u ticker时接收数据库错误

Ruby on rails 使用find\u或\u initialize\u by \u ticker时接收数据库错误,ruby-on-rails,Ruby On Rails,我正在运行一个关联查找\u或\u通过\u ticker方法初始化\u并继续接收 PG::InFailedSqlTransaction: ERROR: current transaction is aborted, commands ignored until end of transaction block 我的头寸有一个stock_id属性,我想检查我的任何头寸是否存在特定的stock对象 如果一个股票对象已经存在,那么我可以抓取它,如果没有,将创建一个新的位置,我可以使用该对象 我在考虑

我正在运行一个关联查找\u或\u通过\u ticker方法初始化\u并继续接收

PG::InFailedSqlTransaction: ERROR:  current transaction is aborted,
commands ignored until end of transaction block
我的头寸有一个stock_id属性,我想检查我的任何头寸是否存在特定的stock对象

如果一个股票对象已经存在,那么我可以抓取它,如果没有,将创建一个新的位置,我可以使用该对象

我在考虑用一个关联扩展编写自己的方法,比如

has_many :positions do
  def find_or_initialize_by_ticker(ticker)
    position_with_ticker = self.select do |position|
      position.stock['symbol'] == ticker
    end
    if position_with_ticker
      position_with_ticker.first
    else
      Position.new
    end
  end
end

这是找工作最有效的方法吗?

你能使用ActiveRecord的内置功能吗

它已经为您构建好了,在数据库上进行过滤要快得多,而不是返回所有行,然后使用
选择
(要传输的数据要少得多)手动过滤它们

如何使用它取决于如何定义
stock
变量:

股票是另一张桌子 Stock是Postgres JSON或HSTORE字段 发件人:


你能用ActiveRecord的内置软件吗

它已经为您构建好了,在数据库上进行过滤要快得多,而不是返回所有行,然后使用
选择
(要传输的数据要少得多)手动过滤它们

如何使用它取决于如何定义
stock
变量:

股票是另一张桌子 Stock是Postgres JSON或HSTORE字段 发件人:

my_model.positions
        .joins(:stock)
        .where(stock: { symbol: ticker })
        .first_or_initialize
# see docs for -> vs ->>
my_model.positions
        .where("stock->>'symbol' = ?", ticker)
        .first_or_initialize