accepts_nested_attributes_for:如果记录重复,如何拒绝记录

时间:2013-12-10 05:06:19

标签: activerecord ruby-on-rails-4

我想拒绝,如果记录重复,这里是代码。

 accepts_nested_attributes_for :member_im_messenger_names, allow_destroy: true  , reject_if: lambda {|attributes| puts attributes.inspect
 attributes['im_screen_name'].blank? or MemberImMessengerName.where('member_id=? AND im_screen_name=? AND im_messenger_name_id=?',self.id,attributes['im_screen_name'],attributes['im_messenger_name_id']).count>0 }

我无法在此代码块中获取当前模型ID。我尝试过self.id和属性[:id],但都是徒劳的。

请建议我如何获得身份证明。因为self.id返回null。

1 个答案:

答案 0 :(得分:0)

我使用以下方法完成了此操作:

accepts_nested_attributes_for :member_im_messenger_names, allow_destroy: true, reject_if: :im_already_exists_or_empty    


def im_already_exists_or_empty(attributed)
   return true if attributed['im_screen_name'].blank? or MemberImMessengerName.where('member_id=? AND im_screen_name=? AND im_messenger_name_id=?',self.id,attributed['im_screen_name'],attributed['im_messenger_name_id']).count>0
   false
end