gpt4 book ai didi

ruby-on-rails-3 - 奇怪的删除空错误

转载 作者:行者123 更新时间:2023-12-04 07:16:12 25 4
gpt4 key购买 nike

我正在尝试从我创建的连接表中删除,但出现了一个我无法弄清楚的奇怪错误。

这是我的模型

class ArticlesUser < ActiveRecord::Base
# attr_accessible :title, :body
belongs_to :user
belongs_to :article
end

class Article < ActiveRecord::Base
attr_accessible :title
belongs_to :user

has_many :articles_users
has_many :likes, :through => :articles_users, :class_name => 'User', :source => :user
end

class User < ActiveRecord::Base
has_many :articles, :order => 'id DESC'
has_and_belongs_to_many :badges

has_many :articles_users
has_many :likes, :through => :articles_users, :class_name => 'Article', :source => :article
end

在 Rails 控制台中测试你可以看到错误:

> a = Article.find(13) 
> a.articles_users #works fine, returns an array of users who "like" the article
> a.articles_users.where(user_id: 3) #works as well
> a.articles_users.where(user_id: 3).first.destroy #this is where the error is thrown!

这里有错误:

 ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'articles_users.' in 'where clause': DELETE FROM `articles_users` WHERE `articles_users`.`` = NULL

为什么它似乎完全忽略了 where hash?请帮我解决这个问题,我今天花了几个小时试图弄明白。

谢谢!

编辑:

articles_users 表有 2 列:article_iduser_id

编辑:

这是从控制台复制粘贴的:

1.9.3p194 :004 > a.articles_users.where(user_id: 3).first
ArticlesUser Load (0.7ms) SELECT `articles_users`.* FROM `articles_users` WHERE `articles_users`.`article_id` = 13 AND `articles_users`.`user_id` = 3 LIMIT 1
=> #<ArticlesUser user_id: 3, article_id: 13>

最佳答案

我尝试并重现了您的问题。

从您的输出看来您在 ArticlesUser 中没有 id 列这就是问题的原因。

=> #<ArticlesUser user_id: 3, article_id: 13> 

我尝试将 id 列添加到表中,效果非常好。创建一个新的迁移并添加它

 add_column :articles_users, :id, :primary_key

当您销毁一条记录时,Rails 使用它的 ID 作为引用将其从数据库中删除。

检查示例。

 DELETE FROM `articles_users` WHERE `articles_users`.`id` = 1

关于ruby-on-rails-3 - 奇怪的删除空错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11662189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com