dangerousdave
dangerousdave

Reputation: 6408

update_all through an association

I am trying to use update_all through an association, and i am getting mysql errors, anyone know why please?

class Basket < ActiveRecord::Base
  has_many :basket_items
  has_many :articles, :through => :basket_items

  def activate_articles
    articles.update_all :active => true
  end
end

class BasketItem < ActiveRecord::Base
  belongs_to :basket
  belongs_to :item
  belongs_to :article
end


Mysql::Error: Unknown column 'basket_items.basket_id' in 'where clause': UPDATE `articles` SET `active` = 1 WHERE ((`basket_items`.basket_id = 114)) 

Upvotes: 2

Views: 2997

Answers (2)

daicoden
daicoden

Reputation: 434

dev.rubyonrails moved it's tickets to github's issue tracker. Here is the moved link: https://github.com/rails/rails/issues/522

@nolman posted this help on the ticket

@daicoden and I at @square were pairing on this and we were able to put something together along the lines of:

class Comment
  class << self
    def trash_all
      sql = "UPDATE #{quoted_table_name} "
      add_joins!(sql, {})
      sql << "SET #{sanitize_sql_for_assignment({:trashed => true})} "
      add_conditions!(sql, {})
      connection.execute(sql)
    end
  end
end

Now you can call todolist.comments(:conditions => {:trashed => false}).trash_all This results in the following SQL:

UPDATE `comments` INNER JOIN `todos` ON `todos`.id = `comments`.todo_id SET `trashed` = 1 WHERE (`comments`.`trashed` = 0 AND `todos`.`todolist_id` = 968316918) 

Hope this helps!

Upvotes: 2

Omar Qureshi
Omar Qureshi

Reputation: 9093

http://dev.rubyonrails.org/ticket/5353

Looks like there was a problem with n-n associations using has_many :through and using update all. Nothing seems to have been done.

1-n associations do appear to work.

Bug?

Upvotes: 2

Related Questions