1

I have a table with data I pull from an external source. It has three different columns that are hierarchical in nature and reference other tables. The foreign keys are NOT constrained however, so data in those fields is not necessarily valid.

I'm trying to write something generic that will print out any records with values that don't reference an existing row in the parent table for a given date.

I've basically got something like this:

klass.where(:date => date).each do |rec|
    next if rec.send(parent)
    # do stuff with rec
end

Where klass is the model for the table and parent is a symbol of a declared 'belongs_to' association.

This method works, however, there may be tens of thousands of records for the day, but unique values on the key are fewer than 100. The repeated lookups into the parent table are unpleasantly time consuming. What I'd like to do is stash all the keys I've already looked up and only perform the lookup on new keys.

Towards this end, I'd like to be able to retrieve the field name that has the foreign key reference at runtime. Ideally this would work regardless of whether or not it's using the default naming convention.

4

1 回答 1

1

您不显示您的模式,但这需要在您的数据库表中进行攻击,而不是在代码中,特别是如果您正在处理“数万”条记录。

作为第一次尝试,我有一个“last_checked”字段,它是一个 DateTime 值。在程序运行开始时,我将捕获该字段的最大值 + 1 秒作为我的last_ran值。任何早于该时间的记录都可以查看。您查看的每条记录都会将该last_checked字段更新为当前DateTime.now值。您可以减少候选记录列表,而无需用这种方式打败 Ruby。

于 2013-10-31T00:09:07.607 回答