开发者

Ruby: DataMapper and has n, :xyz, :through => Resource

开发者 https://www.devze.com 2023-01-30 19:30 出处:网络
I\'ve encountered following issue: there are 2 models: X and Y, they\'re associated with each other like this: has n, :<name>, :through => Resouce; when i\'m doing something like x.ys = array

I've encountered following issue: there are 2 models: X and Y, they're associated with each other like this: has n, :<name>, :through => Resouce; when i'm doing something like x.ys = array_with_50开发者_如何学C0_ys it takes really long time because DataMapper inserts only one association per query (insert into xs_ys(x_id, y_id) values(xid, yid)). This takes really long. The question is: how to make this faster?

Thanks.


Because DataMapper has abstracted the 'back end', the standard behaviour is to insert one record at a time as SQL (or whatever you are using).

Assuming you are using an SQL backend, such as Postgres, you could drop back to raw SQL, and do the following:

x = X.first
query = "INSERT INTO xs_ys(x_id, y_id) VALUES"
vals = []
array_with_500_ys.each do |y|
  vals << "(#{x.id}, #{y.id})"
end

repository.adapter.execute(query + vals.join(','));

This creates one 'insert', passing all records to be inserted. Not sure if this would be any faster, but you could put it into a background job if you need the app not to time out for the user.

0

精彩评论

暂无评论...
验证码 换一张
取 消