Rails中的find_by_sql用于自定义验证

时间:2016-01-19 03:45:19

标签: ruby-on-rails ruby

在轨道上的红宝石中,我像这样两次使用脚手架

rails g scaffold userpost user_field1:string user_field2:string
rails g scaffold adminpost admin_field1:string admin_field2:string

我想进行自定义验证当用户发布userpost时。

用户只能发布用户帖子。管理员只能发布adminpost。并且用户可以发布与admin_field1相同的user_field1和与admin_field2相同的user_field2。

我试过这段代码

class Userpost < ActiveRecord::Base
  validates :check_userpost

  def check_userpost
    admin_field2 = Adminpost.find_by_sql ("SELECT admin_field2 FROM adminposts WHERE admin_field1 = '#{self.user_field1}'")
    if admin_field2 != '#{self.user_field2}'
      errors.add(:user_field2, "not match")
    end
  end
end

如果您有任何想法,请给我建议。

2 个答案:

答案 0 :(得分:0)

希望userpost和adminpost之间没有关系。

def check_userpost
  af1 = Adminpost.where(admin_field1: self.user_field1).first
  af2 = Adminpost.where(admin_field2: self.user_field2).first
  if !af1.nil? && af1.admin_field2 != self.user_feild2
    errors.add(:user_field2, "not match")        
  end
  if !af2.nil? && af2.admin_field1 != self.user_feild1
    errors.add(:user_field1, "not match")        
  end
end

答案 1 :(得分:0)

参考:How do I validate that two values do not equal each other in a Rails model?

可观察到的差异:

  1. “验证”不是“验证”
  2. 为什么在使用ActiveRecord时使用SQL?

    class Userpost < ActiveRecord::Base
      validate :check_userpost
    
      def check_userpost
        tmp = Adminpost.find_by_admin_field1(self.user_field1)
        if tmp and tmp.admin_field2 != self.user_field2
          errors.add(:user_field2, "not match") 
        end
      end
    end
    
  3. 通过谷歌搜索疯狂刺痛......