Rails 避免重复数据库条目(许多属性)
Rails avoiding duplication of database entry(many attributes)
有没有办法让模型执行类似flash[:notice]
的错误信息??
我想避免将相同的数据输入我的数据库两次..
before_save :no_duplication
private
def no_duplication
if CarPrice.where(:car_id => self.car_id).where(:agent_id => self.agent_id).blank?
return true
else
return false
end
end
此代码停止复制,但不发送任何错误消息。我该如何解决?
我更愿意使用模型验证:
validates :car_id, uniqueness: { scope: :agent_id }
查看文档了解其他选项,例如 allow_nil: true 等 http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html
我还建议添加唯一索引:
add_index :name_of_table, [:car_id, :agent_id], unique: true
有没有办法让模型执行类似flash[:notice]
的错误信息??
我想避免将相同的数据输入我的数据库两次..
before_save :no_duplication
private
def no_duplication
if CarPrice.where(:car_id => self.car_id).where(:agent_id => self.agent_id).blank?
return true
else
return false
end
end
此代码停止复制,但不发送任何错误消息。我该如何解决?
我更愿意使用模型验证:
validates :car_id, uniqueness: { scope: :agent_id }
查看文档了解其他选项,例如 allow_nil: true 等 http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html
我还建议添加唯一索引:
add_index :name_of_table, [:car_id, :agent_id], unique: true