Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update_all problem #19

Open
chip-and-dail opened this issue Oct 24, 2014 · 1 comment
Open

update_all problem #19

chip-and-dail opened this issue Oct 24, 2014 · 1 comment

Comments

@chip-and-dail
Copy link

I use active_record-acts_as. Did everything as described in the example. But now I want to make update_all and it does not work. Tried to use joins, but the query that is generated is of course wrong. I want to change all Products whose pens.color = 'red'. What am I doing wrong?

models:

class Pen < ActiveRecord::Base
    acts_as :product
end

class Product < ActiveRecord::Base
  actable
end

problem place:

Pen.joins(:product).where("pens.color = 'red'").update_all("products.price = 1")

sql generated:

UPDATE "pens" 
SET products.price = 1 
WHERE "pens"."id" IN 
(
    SELECT "pens"."id" 
    FROM "pens" 
    INNER JOIN "products" ON "products"."actable_id" = "pens"."id" AND "products"."actable_type" = 'Pen' 
    WHERE (pens.color = 'red')
)

Of course, in the query you can see that it is impossible to make set products when update pens. But how to fix it?

How to change to the correct query:

    UPDATE products as p
    set price = 1
    from pens
    WHERE pens."id" = p.actable_id and pens.color = 'red' and p.actable_type = 'Pen'

?

@kinkou
Copy link

kinkou commented Jun 17, 2015

I can confirm that the problem exists:

> Tv.update_all(name: 'Samsung').to_sql
  SQL (0.4ms)  UPDATE "tvs" SET "name" = 'Samsung'
PG::Error: ERROR:  column "name" of relation "tvs" does not exist
LINE 1: UPDATE "tvs" SET "name" = 'Samsung'
                                     ^

So far, I guess, you need to do it 'by hand': Product.where("actable_id IN (SELECT id FROM tvs where color='red')").update_all(name: 'Samsung')

jeremyyap pushed a commit to Coursemology/active_record-acts_as that referenced this issue Oct 23, 2018
Restore functionality that resolves belongs_to members in child classes when performing queries.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants