1

Using Rails 3.2. Previously I did this to destroy, but now I don't wanna destroy, but just mark them as inactive instead:

Shop.find_by_sql("SELECT id FROM #{ActiveRecord::Base.connection_config[:database]}.shops AS shops
  LEFT OUTER JOIN thirdparty.othershoplist AS other_shops
  ON shops.other_shop_id = other_shops.ShopID
  WHERE other_shops.ShopID IS NULL").map(&:destroy)

Now I don't want to destroy the records, but wanna set the column for shop.shop_status as inactive for the return set.

Shop.find_by_sql("SELECT id FROM #{ActiveRecord::Base.connection_config[:database]}.shops AS shops
  LEFT OUTER JOIN thirdparty.othershoplist AS other_shops
  ON shops.other_shop_id = other_shops.ShopID
  WHERE other_shops.ShopID IS NULL").update_all(shop_status: 'inactive')

But this is not working because the return set is an array. How can I achieve this as simple as possible (perhaps a one liner)?

2
  • For which records in your shop you are trying to update shop_status as inactive? I mean what is your SQL query? Commented Apr 27, 2014 at 17:28
  • Why not use sql 'update' ? Commented Apr 27, 2014 at 18:41

1 Answer 1

2

Assuming you want to leave that SQL query as is, I would do this:

ids = Shop.find_by_sql("SELECT id
       FROM #{ActiveRecord::Base.connection_config[:database]}.shops AS shops
       LEFT OUTER JOIN thirdparty.othershoplist AS other_shops
       ON shops.other_shop_id = other_shops.ShopID
       WHERE other_shops.ShopID IS NULL")
Shop.where(id: ids).update_all(shop_status: 'inactive')
Sign up to request clarification or add additional context in comments.

4 Comments

Can't do it in one liner?
Well, you could put that big "Shop.find_by_sql" line where "ids" is in the second line and it would technically be one line. Or you could rewrite that find_by_sql...
Care to give an example? Thanks.
@Victor - ids = Shop.where(id: Shop.find_by_sql("SELECT id FROM #{ActiveRecord::Base.connection_config[:database]}.shops AS shops LEFT OUTER JOIN thirdparty.othershoplist AS other_shops ON shops.other_shop_id = other_shops.ShopID WHERE other_shops.ShopID IS NULL")).update_all(shop_status: 'inactive') ... thats the one-liner

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.