I'm trying to delete from a join table I made and I'm getting a weird error I cant figure out.
Here are my models
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
Testing in the Rails Console you can see the error:
> 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!
Here is there error:
ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'articles_users.' in 'where clause': DELETE FROM `articles_users` WHERE `articles_users`.`` = NULL
Why does it seem to be completely ignoring the where hash? Please help me with this I've spent hours today trying to figure it out.
Thanks!
Edit:
The articles_users table has 2 columns: article_id and user_id
Edit:
This is copy and pasted from the console:
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>
I tried and reproduced your issue.
From Your output it seems you don't have a id column in ArticlesUser which is the cause if issue.
=> #<ArticlesUser user_id: 3, article_id: 13>
I tried adding id column to the table and it worked like charm. Created a new migration and add it
add_column :articles_users, :id, :primary_key
When you destroy a record rails uses its id as a reference to delete it from database.
Check example.
DELETE FROM `articles_users` WHERE `articles_users`.`id` = 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With