update_all through an association

£可爱£侵袭症+ 提交于 2019-12-22 12:37:29

问题


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)) 

回答1:


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?




回答2:


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!



来源:https://stackoverflow.com/questions/3833529/update-all-through-an-association

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!