代码之家  ›  专栏  ›  技术社区  ›  dangerousdave

通过关联更新

  •  2
  • dangerousdave  · 技术社区  · 14 年前

    我正试图通过一个关联使用update_,我得到了mysql错误,有人知道为什么吗?

    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)) 
    
    2 回复  |  直到 13 年前
        1
  •  2
  •   Omar Qureshi    14 年前

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

    看起来使用has-u many的n-n关联有问题:通过和使用update all。似乎什么都没做。

    1-n关联确实有效。

    缺陷?

        2
  •  2
  •   daicoden    13 年前

    dev.rubyonrails把它的票移到了github的问题跟踪程序。这是移动的链接: https://github.com/rails/rails/issues/522

    @诺尔曼把这个帮助贴在罚单上

    @我们在@square的Daicoden和我在一起,我们可以把一些东西放在一起:

    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
    

    现在,您可以调用todolist.comments(:conditions=>:trashed=>false)。全部清除。 这将导致以下SQL:

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

    希望这有帮助!