Rails has_many:通过依赖:destroy表现得非常奇怪

时间:2013-04-01 19:25:56

标签: ruby-on-rails has-many-through

用户:

class User < ActiveRecord::Base

  attr_accessible :email, :username, :password, :password_confirmation, :remember_me

  has_many :tasks_users, :dependent => :destroy, :conditions => {:is_owner => true}
  has_many :tasks, :through => :tasks_users, :source => :task

任务:

class Task < ActiveRecord::Base
  include RankedModel
  ranks :sort_order

  acts_as_taggable

  has_many :tasks_users  
  has_many :users, :through => :tasks_users

TasksUser:

class TasksUser < ActiveRecord::Base
    attr_accessible :is_owner
    belongs_to :user
    belongs_to :task

    validates_uniqueness_of :user_id, :scope => [:user_id, :task_id]
end

他们这里的关键是依赖毁灭。

每当我试图销毁我的用户,这应该破坏连接模型,我最终得到这个奇怪的SQL错误:

User Load (0.1ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 17]]
   (0.1ms)  begin transaction
  ActsAsTaggableOn::Tagging Load (0.1ms)  SELECT "taggings".* FROM "taggings" WHERE "taggings"."tagger_id" = 17 AND "taggings"."tagger_type" = 'User'
  TasksUser Load (0.1ms)  SELECT "tasks_users".* FROM "tasks_users" WHERE "tasks_users"."user_id" = 17 AND "tasks_users"."is_owner" = 't'
Could not log "sql.active_record" event. NoMethodError: undefined method `name' for nil:NilClass
**SQLite3::SQLException: no such column: tasks_users.: DELETE FROM "tasks_users" WHERE "tasks_users"."" = ?**
   (0.1ms)  rollback transaction
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: tasks_users.: DELETE FROM "tasks_users" WHERE "tasks_users"."" = ?
from /home/steveq/.rvm/gems/ruby-1.9.3-p194@rails32/gems/sqlite3-1.3.7/lib/sqlite3/database.rb:91:in `initialize'

带有双星号的行是有问题的行 - 它似乎是在“tasks_users”中搜索记录。“”。

如果我所做的就是改变:conditions =&gt; {:is_owner =&gt; false},sql执行没有问题:

  User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 17]]
   (0.1ms)  begin transaction
  ActsAsTaggableOn::Tagging Load (0.2ms)  SELECT "taggings".* FROM "taggings" WHERE "taggings"."tagger_id" = 17 AND "taggings"."tagger_type" = 'User'
  TasksUser Load (0.1ms)  SELECT "tasks_users".* FROM "tasks_users" WHERE "tasks_users"."user_id" = 17 AND "tasks_users"."is_owner" = 'f'
  List Load (0.2ms)  SELECT "lists".* FROM "lists" WHERE "lists"."owner_id" = 17
  Relationship Load (0.1ms)  SELECT "relationships".* FROM "relationships" WHERE "relationships"."user_id" = 17
  SQL (0.3ms)  DELETE FROM "users" WHERE "users"."id" = ?  [["id", 17]]
   (299.4ms)  commit transaction

关于这里发生了什么的想法,以及为什么让is_owner的条件从true变为false允许查询和删除语句执行?

由于

1 个答案:

答案 0 :(得分:1)

呃 - 希望我可以拯救别人不要撞这堵墙一小时。

问题是我如何指定:条件。

需要用双引号括起来:

  has_many :tasks_users, :dependent => :destroy, :conditions => "is_owner = 'true'"

就是这样。