accepts_nested_attributes_for和validates_uniqueness_of生成错误的sql请求

时间:2015-05-30 15:30:26

标签: ruby-on-rails validation rails-activerecord

我有奇怪的验证请求。这是我的代码:

#app/models/user.rb
class User < ActiveRecord::Base
  has_many :exchanges_users, inverse_of: :user
end

#app/models/exchange.rb
class Exchange < ActiveRecord::Base
  has_many :exchanges_users, inverse_of: :exchange
  accepts_nested_attributes_for :exchanges_users, :allow_destroy => true, :reject_if => :all_blank
end

#app/models/exchanges_user.rb
class ExchangesUser < ActiveRecord::Base
  validates_presence_of :exchange
  validates_presence_of :user
  validates_uniqueness_of :exchange, :scope => [:user]

  belongs_to :exchange, inverse_of: :exchanges_users
  belongs_to :user, inverse_of: :exchanges_users
end

并且,在控制台中,当我尝试创建Exchange时:

e = Exchange.new({"name"=>"Test", "exchanges_users_attributes"=>{"0"=>{"user_id"=>"4"}, "1"=>{"user_id"=>"1"}}}) ; e.save

Rails验证这些请求的唯一性:

SELECT  1 AS one FROM "exchanges_users" WHERE ("exchanges_users"."exchange_id" IS NULL AND "exchanges_users"."user_id" = 4) LIMIT 1
SELECT  1 AS one FROM "exchanges_users" WHERE ("exchanges_users"."exchange_id" IS NULL AND "exchanges_users"."user_id" = 1) LIMIT 1

显然,&#34; IS NULL&#34;部分是错误的,但我不知道为什么会发生这种情况。你有什么想法吗?

1 个答案:

答案 0 :(得分:1)

由于您有netstat -ntlpd | grep 1026此查询应该是良性的,但无用。您可以先创建validates_presence_of :exchange记录并应用其属性

来解决此问题
Exchange