在验证之前做一些事情,没有方法错误

时间:2015-08-11 13:01:36

标签: ruby-on-rails ruby-on-rails-4

我有一个通知模型。 用户或联系人可以发布通知。 并且通知可以转到商家或notification_area。

必须填写人员,因此如果没有添加用户,则必须填写登录的联系人。

必须填写notification_to,因此当没有添加业务时,必须采用纬度和经度并添加正确的区域。

我已编写代码但不起作用。 首先我把它添加到控制器中。但在浏览谷歌和这个网站后,我发现我必须将它添加到模型中。

但它仍然无效。

我做错了什么? 我收到错误

class Notification < ActiveRecord::Base
   belongs_to :people, :polymorphic => true
   belongs_to :notification_to, :polymorphic => true
   belongs_to :App_of_area
   belongs_to :kind

   before_validation :if_empty_add_the_other

   #validates :photo, presence: true
   validates :message, :status, :people_id, :people_type, :notification_to_id, :notification_to_type, :App_of_area_id, :kinds_id, presence: true


   def if_empty_add_the_other
     unless self.people_type.present?
        self.people = current_contact
     end
     unless self.notification_to_id.present?
        if self.longitude && self.latitude
            @noa = NotificationArea.where( "latitude_A <= #{self.latitude} AND latitude_B >= #{self.latitude} AND longitude_A <= #{self.longitude} AND longitude_B >= #{self.longitude}")
            self.notification_to = @noa.first
         end
       end
     end
   end

end

1 个答案:

答案 0 :(得分:0)

首先,您需要DRY代码:

belongs_to :business
belongs_to :app_of_area
has_many :people, source_type: "Notification"
has_many :api_keys

before_validation :if_empty_add_the_other

has_secure_password 

validates :name, :email, :rights, :password_confirmation, :app_of_area_id, :business_id, presence: true
validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
validates :email, uniqueness: true
validates :password, confirmation: true, length: { minimum: 6 }

:as用于多态关联,我相信你想使用:source_type,如上所示。这样您就可以执行self.people << current_contact,但我会在下面解决此问题。

为什么:App_of_area大写?与:App_of_area_id相同?

您的if_empty_add_the_other验证方法有很多错误。

  • 使用unless而不是if not
  • 测试纬度和经度的两个if语句是否可以合并到if self.longitude && self.latitude

你必须问自己,current_contact如何传递给这个函数?此外,您正试图将self.people 设置为等于此幻像current_contact; self.people将包含多个记录,如果您愿意,则包含一个数组,因此设置一个等于一个对象的数组将无法工作,因此上面的self.people << current_contact